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 :
using System;
class Geeks {
public static void Main( string [] args)
{
string s1 = "GeeksforGeeks" ;
string s2 = "" ;
string s3 = null ;
bool b1 = string .IsNullOrEmpty(s1);
bool b2 = string .IsNullOrEmpty(s2);
bool b3 = string .IsNullOrEmpty(s3);
Console.WriteLine(b1);
Console.WriteLine(b2);
Console.WriteLine(b3);
}
}
|
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
using System;
class Geeks {
public static bool check( string s)
{
return (s == null || s == String.Empty) ? true : false ;
}
public static void Main( string [] args)
{
string s1 = "GeeksforGeeks" ;
string s2 = "" ;
string s3 = null ;
bool b1 = check(s1);
bool b2 = check(s2);
bool b3 = check(s3);
Console.WriteLine(b1);
Console.WriteLine(b2);
Console.WriteLine(b3);
}
}
|
Reference: https://msdn.microsoft.com/en-us/library/system.string.isnullorempty(v=vs.110).aspx
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!