How to Check whether a String is Null or Empty in .NET


If you have a string variable in your program and you want to check whether it is empty or null you have following options:

string a = null; 
string b = "";​

To check whether string is null you can use = = operator

Console.WriteLine(a == null);

To Check whether string is empty you can either use = = operator by comparing it with String.Empty property or you can use Equals() method of string class as shown below:

Console.WriteLine(b.Equals("")); 
Console.WriteLine(b == String.Empty);

To check both null and empty in one statement you can use IsNullOrEmpty method of string class

Console.WriteLine(String.IsNullOrEmpty(a)); 
Console.WriteLine(String.IsNullOrEmpty(b));

 

 

About author


User avatar

Waqas Anwar

Founder of EzzyLearning.com, Senior Consultant, Microsoft .NET and Web Technologies

Comments