Open In App

C# | IsNullOrEmpty() Method

Last Updated : 01 Apr, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

In C#, IsNullOrEmpty() is a string method. It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned “” or String.Empty (A constant for empty strings).

Syntax:

public static bool IsNullOrEmpty(String str)  

Explanation: This method will take a parameter which is of type System.String and this method will returns a boolean value. If the str parameter is null or an empty string (“”) then return True otherwise return False.

Example:

Input : str  = null         // initialize by null value
        String.IsNullOrEmpty(str)
Output: True

Input : str  = String.Empty  // initialize by empty value
        String.IsNullOrEmpty(str)
Output: True

Program: To demonstrate the working of the IsNullOrEmpty() Method :




// C# program to illustrate 
// IsNullOrEmpty() Method
using System;
class Geeks {
    
    // Main Method
    public static void Main(string[] args)
    {
        string s1 = "GeeksforGeeks";
      
        // or declare String s2.Empty;
        string s2 = ""
  
        string s3 = null;
  
        // for String value Geeks, return true
        bool b1 = string.IsNullOrEmpty(s1);
  
        // For String value Empty or "", return true
        bool b2 = string.IsNullOrEmpty(s2);
  
        // For String value null, return true
        bool b3 = string.IsNullOrEmpty(s3);
  
        Console.WriteLine(b1);
        Console.WriteLine(b2);
        Console.WriteLine(b3);
    }
}


Output:

False
True
True

Note: IsNullOrEmpty method enables to check whether a String is null or its value is Empty and its alternative code can be as follows:

return  s == null || s == String.Empty;

Program: To demonstrate IsNullOrEmpty() method’s alternative




// C# program to illustrate the 
// similar method for IsNullOrEmpty()
using System;
class Geeks {
  
    // to make similar method as IsNullOrEmpty
    public static bool check(string s)
    {
        return (s == null || s == String.Empty) ? true : false;
    }
  
    // Main Method
    public static void Main(string[] args)
    {
        string s1 = "GeeksforGeeks";
  
        // or declare String s2.Empty;
        string s2 = ""
        string s3 = null;
  
        bool b1 = check(s1);
        bool b2 = check(s2);
        bool b3 = check(s3);
  
        // same output as above program
        Console.WriteLine(b1);
        Console.WriteLine(b2);
        Console.WriteLine(b3);
    }
}


Output:

False
True
True

Reference: https://msdn.microsoft.com/en-us/library/system.string.isnullorempty(v=vs.110).aspx



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads