Difference between Null and Empty (Blank) Strings?

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

string s = "";

By contrast, a null string does not refer to an instance of a System. String object and any attempt to call a method on a null string results in 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 does not cause an exception to be thrown:

string str = "hello";
string nullStr = null;
string emptyStr = "";
string tempStr  = str + nullStr; // tempStr = "hello"
bool b = (emptyStr == nullStr);// b = false;
emptyStr + nullStr = ""; // creates a new empty string
int I  = nullStr.Length; // throws NullReferenceException

Tagged . Bookmark the permalink.

Leave a Reply