Sunday, July 31, 2011

C# Guideline: Use String.Empty When You Can

Whenever you are tempted to write “” as a string somewhere in your C# code use String.Empty instead. What is the difference? Technically one is a constant while the other is a read-only static field. There is no difference in behavior in this case. However be aware that both are different in their implementation.

The inline constant “” is introduce at compile time. This means once it has been compile it cannot be changed any more.

With the read-only field it is a little different. During compile time only a reference to the field is added. This value of this field is then read during runtime.

This can be quite a difference. For example if the read-only property is define in a different assembly and then you update that assembly with the read-only property now having a different value, that new value will then be used from then on.

Why do I believe this is a good guideline for C#? When you add your own “constants” you typically want to define and maintain them in one place only. With a static property you can achieve that. The code then looks as follows:

public class Foo {
   public static string LastName = "Smith";
}

And here is how you then use it:

public void Bar() {
   var address = "Mr. " + Foo.LastName;
   // ... remainder left out
}

If you ever need to change the LastName value you only need to change it in one place. Although String.Empty is very unlikely to change, for consistency reasons you should use it rather than “”.

The same guideline applies to all other types of constants as well, e.g. Type.EmptyTypes.

There is (at least) one exception to the use of String.Empty. If you have a switch statement on a string and one of the cases is String.Empty you will find that it won’t compile. The ‘case’ statement requires a constant (which evaluate at compile time) and doesn’t allow for read-only fields (which evaluate at runtime). So the only option then is to write the following:

switch(aString) {
   case "": // Can't write ‘case String.Empty:’ here!
      // something important to happen here
      break;
}

0 comments:

Post a Comment

All comments, questions and other feedback is much appreciated. Thank you!