C# I IsNullOrEmpty() Method

In this article we’ll learn about C# I IsNullOrEmpty() Method. This method is named as IsNullOrEmpty() and it is an extension methods of string class. It is used to check whether the given string is null or an Empty. It checks for both i.e null and empty. A string will be null if it has not been assigned a value and it will be empty if it is assigned “” or String.Empty into it. 

This method will take a System.String type parameter and will returns a boolean value based upon the input. If it will be null or an empty, then True else False will be returned.

        string name  = null            // initialize it with null value

       //Output will be: True

       string name  = String.Empty       // initialize it with empty value
       //Output will be: True

       //you can also check it without above method as(if you want).
       if(name!= null || name !="")
         //perform you action here 

Let’s check it using one example below:

class CodeConfig
    // create one method to test IsNullOrEmpty method
   public static bool checkText(string str)
       //we used turnery operator below instead of if-else 
        return (str == null || str == String.Empty) ? true : false;  
   public static void Main(string[] args)
        //declaring 3 string variables
         string v1 = "Code config";    // string with some text 
         string v2 = "";                //string with empty text 
         string v3 = null;              // string with null in it 
        bool b1 = checkText(v1);
        bool b2 = checkText(v2);
        bool b3 = checkText(v3);
        // let's check the output now
        Console.WriteLine("First string value output= "+ b1);
        Console.WriteLine("Second string value output= "+ b2);
        Console.WriteLine("Third string value output= "+ b3);

What will be the output, for better understanding try above code yourself in visual studio. You can check more such topics HERE and also do check our Interview Section.

You may like