C# String - IsNullOrEmpty() Method



The C# String IsNullOrEmpty() method is used to check whether the specified string is null or an empty string (" ").

A string considered to be null if it has not been assigned a value, while a string is empty if it is assigned only an empty pair of double quotes ("") or String.Empty().

Syntax

Following is the syntax of the C# string IsNullOrEmpty() method −

public static bool IsNullOrEmpty (string? value);

Parameters

This method accepts a string value as a parameter representing the string to be checked.

Return Value

This method returns true if the value parameter is null or an empty string (""); otherwise, false.

Example 1: Check Whether String is Empty

Following is a basic example of the IsNullOrEmpty() method to check whether string is empty or not −

  
using System;
class Program {
   static void Main() {
      string str = "";
      bool res = string.IsNullOrEmpty(str);
      if (res == true) {
         Console.WriteLine("String is empty.");
      }
      else {
         Console.WriteLine("String is neither empty nor null.");
      }
   }
}

Output

Following is the output −

String is empty.

Example 2: Check Whether String is Null

Let's look at another example. Here, we use the IsNullOrEmpty() method to check string is null or not −

using System;
class Program {
   static void Main() {
      string str = null;
      bool res = string.IsNullOrEmpty(str);
      if (res == true) {
         Console.WriteLine("String is null");
      }
      else {
         Console.WriteLine("String is not null.");
      }
   }
}

Output

Following is the output −

String is null

Example 3: Differentiate Between Null and Empty

In the following example, we differentiate between null and empty strings without using the IsNullOrEmpty method −

using System;
class Program {
   static void Main() {
      string str = null;
      if (str == null) {
         Console.WriteLine("String is null.");
      }
      else if (str == string.Empty) {
         Console.WriteLine("String is empty.");
      }
      else {
         Console.WriteLine("String is not null or empty.");
      }
   }
}

Output

Following is the output −

String is null.

Example 4: What If String is Neither Null nor Empty

The example below uses the IsNullOrEmpty() method to check if a string is empty or null. If the string is neither null nor empty, it will display false −

using System;
class Program {
   static void Main() {
      string str = "Hello TP";
      bool res = string.IsNullOrEmpty(str);
      if(res == true){
         Console.WriteLine("String is either Empty or Null");
      }
      else{
         Console.WriteLine("String is neither Empty nor Null");
         Console.WriteLine("string value: {0}", str);
      }
   }
}

Output

Following is the output −

String is neither Empty nor Null
string value: Hello TP
csharp_strings.htm
Advertisements