How to check if a String is null or Empty in C#

Checking a String value to see if it is Empty or null is something you will come across a lot during your day to day work using C#. There are different ways to doing this check in C#. Basically there are different ways you can do this. String is a reference type so you can check if it is null. Also you can check for an empty string (“”) or check the length of the string and see if it is zero.

How to Check null in C# (C Sharp)

How to Check Empty String in C#

Here I have given different examples of how to check if a String is null or Empty in C#

Example 1

   public static String Test(string s)

    {

    if (s == null || s == String.Empty)

        return "is null or empty";

    else

        return String.Format("(\\"{0}\\") is not null or empty", s);

    }

 

 

Example 2

   public static String Test(string s)

    {

    if (String.IsNullOrEmpty(s))

        return "is null or empty";

    else

        return String.Format("(\\"{0}\\") is not null or empty", s);

    }

 

Example 3

    public static String Test(string s)

    {

    if (String.IsNullOrEmpty(s) == true)

        return "is null or empty";

    else

        return String.Format("(\\"{0}\\") is not null or empty", s);

    }

 

Example 4

public static String Test(string s)

        {

            if (myVar == null || myVar.Length == 0)

                return "is null or empty";

            else

                return String.Format("(\\"{0}\\") is not null or empty", myVar);

        }

 

Example 5

Convert.ToString((object)stringVar) == "";

 

Hope that was helpful.

Robert