Empty string and array best practices in C#

Photo by Nel Ranoko on Unsplash

Empty string and array best practices in C#

Just a very short blog post... for everyone who is not yet known to it. Since .Net Framework 4.6 for two immutable types we got new static fields in the framework:

// instead of
string foo = "";
byte[] bar = new byte[0];

// prefer
string foo = string.Empty;
byte[] bar = Array.Empty<byte>();

If you are now asking yourself why you should use this - string and array are immutable (they will always be created new when the content does change and the old memory is garbaged). By using the static fields there is no additional memory location for the value of the variable, it will always be the same.

Naturally, you will first note a real impact if you are creating very much strings and/or arrays. But it is always better to follow best practices from the beginning instead of running into problems afterwards...