What is the difference, in practice, between "" and String.Empty?


In .NET you can see the multiple ways to initialize a string with an empty value, commonly known as "double quote".

Is there a proper way to do this? And what would be the practical difference between using:

  • var nome = String.Empty;
  • var nome = "";

I also know that you still have string and String in C #, but you've been seen here that there is no difference in the use of both.

asked by anonymous 05.09.2016 / 15:33

2 answers


Zero practical difference. string.Empty is equal to "" .

In the past until there was some , then some people recommended using the "constant" rather than the literal, but today each one uses whatever it finds most readable and eventually is compacted with the team

I use "" , because in some places the "constant" can not be used (because technically it is not a constant but a readonly field). This is true for switch-case , default argument, attributes, and any other location that requires a constant that can be fully resolved at compile time.

If you're concerned with performance, there's a benchmark in SO with IL code comparisons and Assembly .

More information can be obtained in source code .

The Documentation Explicitly Says It's the Same .

Because of interning (there is no creation of a new instance in either There is only one empty string instance allocated in the static area of the application, and all variables that have this value point to the same instance (the source is a response on the Jon Skeet OS ). It uses the Flyweight pattern / a>.

05.09.2016 / 15:40

There is really no difference from the point of view of performance and code generated. In performance tests, they went back and forth, among which one was faster against the other, and only for milliseconds.

In looking at the behind the code, you really do not see any difference either. The only difference is IL , which string.Empty use the ldsfld and "" operation code uses the ldstr operation code, but this is just because string.Empty is static, and both statements do the same thing.

If you look at the set of what is produced, it is exactly the same.

One difference is that if you use the syntax of a switch-case , you can not write case string.Empty: because it is not a constant and you will have Compilation error : A constant value is expected .

As in the example below.

using System;

public class Program
    public static void Main()
        string teste = "";

        switch (teste)
             case "":
                Console.WriteLine("Case 1");
            case String.Empty:
                Console.WriteLine("Case 2");


Compilation error (line 14, col 9): A constant value is expected

So user what you find more readable, however. It is subjective and varies from person to person - so I suggest you find out what most people on your team use, and who all do the consistency.

I personally find String.Empty easier to read.

05.09.2016 / 16:06