CopyPastehas never been so tasty!

Check null or empty string in C#

by anonymous

  • 0
  • 0
  • 0
81 views

Null or Empty String:

 

To check whether the string is null or empty we use the string class and its method is ‘IsNullOrEmpty’ it takes a string as parameter and check string reference is null or empty. It is a Boolean method and it will return true if the string is empty or null and return false if string is not empty or null.

 

To understand let us consider an example in which we have three strings. The first string is null, second is empty means that is equals to “” have zero length and last string has some value. We pass these strings in ‘IsNullOrEmpty’ method as parameter and check that the strings are null or empty.

 

To demonstrate make a console application and write the following code.

 

 

Code:

 

 

classCheck_null_or_empty_string

    {

staticvoid Main(string[] args)

        {

string s = null;

string s1 = "";

string s2 = "i am not empty";

if (string.IsNullOrEmpty(s))

            {

Console.WriteLine("string is null");

            }

else

            {

Console.WriteLine("string is not null");

            }

if (string.IsNullOrEmpty(s1))

            {

Console.WriteLine("string is empty");

            }

else

            {

Console.WriteLine("string is not empty");

            }

if (string.IsNullOrEmpty(s2))

            {

Console.WriteLine("string is null or empty");

            }

else

            {

Console.WriteLine("string is not empty or null");

            }

Console.ReadLine();

        }

    }

 

Add A Comment: