What is the difference between string.Empty and “”


Functionally both represent the string is empty but there are some minor differences between both

string.Empty
It is read-only field, which can’t be used as a compile time constant or in switch statements

public class HelloWorld
{
public void Display(string name=string.Empty)
{
Console.WriteLine(“Display method”);
}

public static void Main(string[] args)
{
    HelloWorld h = new HelloWorld();
    h.Display();

}
Enter fullscreen mode

Exit fullscreen mode

}
The above code will give a compile-time error:

error CS1736: Default parameter value for ‘name’ must be a compile-time constant

Similarly, string.Empty can’t be used in a switch case.

Whereas “” (an empty string literal)
It is considered a compile-time constant.

Compile-time Constant

The constant value will be fixed during the compilation rather than at runtime

using System;

public class HelloWorld
{
public void Display()
{
string val = “”;
Console.WriteLine(“Empty string:”+val);
}

public static void Main(string[] args)
{
    HelloWorld h = new HelloWorld();
    h.Display();

}
Enter fullscreen mode

Exit fullscreen mode

}

Here, the value will fixed at the time of compilation

Output
Empty string:



Source link