There is really no difference from the point of view of performance and generated code. In performance tests, they went there and here, among which one was faster against the other, and only by milliseconds.
In looking behind the code, you don’t really see any difference either. The only difference is in the IL
, that string.Empty
use the operation code ldsfld
and ""
uses the operation code ldstr
, but that’s only because string.Empty
is static, and both instructions do the same thing.
If you look at the whole of what is produced, it is exactly the same.
One difference is that if you use in the syntax of a switch-case
, you can’t write case string.Empty:
because it is not a constant and you will have a 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");
break;
case String.Empty:
Console.WriteLine("Case 2");
break;
}
}
}
Compilation error (line 14, col 9): A Constant value is expected
So user whatever you find readable, though. It’s subjective and varies from person to person - so I suggest you find out what most people on your team use, and that everyone makes consistency.
Personally I think String.Empty
easier to read.
I’m not sure about that, but maybe the guy
string
in C# is also an object. There, in this case,string.Empty
would be a predefined instance of an empty string, and so its attribution to a new string simply makes a copy of that instance. Whereas""
in fact it is in fact an empty string, and its assignment literally constructs a new instance from that "empty value" (as if it were "received as parameter" in the constructor). I thought it was worth this (possible) detailing, although you’re absolutely right: zero practical difference. :)– Luiz Vieira
@Luizvieira updated showing that this does not happen in practice.
– Maniero
Very good part about the interning. I didn’t know. :)
– Luiz Vieira