User Experience

Null strings and empty strings

6 min read

  • June 15, 2024
  • Rajesh Goel

An empty string is an instance of a System.String object that contains zero characters. Empty strings are used often in various programming scenarios to represent a blank text field. You can call methods on empty strings because they're valid System.String objects. Empty strings are initialized as follows:

string s = String.Empty;

By contrast, a null string doesn't refer to an instance of a System.String object and any attempt to call a method on a null string causes a NullReferenceException. However, you can use null strings in concatenation and comparison operations with other strings. The following examples illustrate some cases in which a reference to a null string does and doesn't cause an exception to be thrown:

string str = "hello"; 
string? nullStr = null; 
string emptyStr = String.Empty; 

string tempStr = str + nullStr; 
// Output of the following line: hello 
Console.WriteLine(tempStr); 

bool b = (emptyStr == nullStr); 
// Output of the following line: False 
Console.WriteLine(b);  

// The following line creates a new empty string.  
string newStr = emptyStr + nullStr;  

// Null strings and empty strings behave differently. The following  
// two lines display 0.  
Console.WriteLine(emptyStr.Length);  
Console.WriteLine(newStr.Length);  
// The following line raises a NullReferenceException.  
//Console.WriteLine(nullStr.Length);  

// The null character can be displayed and counted, like other chars.  
string s1 = "\x0" + "abc";  
string s2 = "abc" + "\x0";  
// Output of the following line: * abc  
Console.WriteLine("*" + s1 + "*");  
// Output of the following line: *abc  
Console.WriteLine("*" + s2 + "*");  
// Output of the following line: 4  
Console.WriteLine(s2.Length);