Mega Code Archive

 
Categories / C# Book / 02 Essential Types
 

0232 Empty string vs null string

string is a reference type therefore we can assign null to string variable. using System; class Sample { public static void Main() { string s = null; } } Empty string is a string with no characters. The length of an empty string is 0. Empty string is not nullstring. using System; class Sample { public static void Main() { string s = ""; Console.WriteLine(s.Length); } } The output: 0 From the code above we can see that the length of a empty string is 0. We cannot check the Length property on an empty string. using System; class Sample { public static void Main() { string s = null; Console.WriteLine(s.Length); } } The output: Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. at Sample.Main()