C# isNullOrEmpty method explanation with examples

C# isNullOrEmpty method

C# isNullOrEmpty method is used to check if a string is null or if it is empty. There is a difference between null and empty string. A string is a null string if no value is assigned to it. It is empty if we assign "" or String.Empty. String.Empty is a constant for empty string.

In this post, we will learn how to use isNullOrEmpty method, its definition and some examples.

Null and Empty String in C#:

A string is called a null string if we haven’t assigned any value to it. Or, if we have assigned null explicitly to it.

An empty string is a string with a value of "" or if we assign explicitly String.Empty to it.

The length of an empty string is 0 , but if we try to get the length of an empty string, it will throw one NullReferenceException. That’s the reason isNullOrEmpty is important. We can add one check with this method to avoid any exceptions.

Definition of isNullOrEmpty:

isNullOrEmpty method is defined as below:

public static bool IsNullOrEmpty (string? value);

It takes one string as its parameter. It checks if the string is null or empty and based on that, it returns one boolean value.

Example of isNullOrEmpty:

Let’s take a look at the below example:

using System;
					
public class Program
{
	public static void Main()
	{
		string firstStr = "";
		string secondStr = "Hello";
		string thirdStr = "   ";
		string fourthStr = null;
		string fifthStr = String.Empty;
		
		Console.WriteLine("firstStr "+String.IsNullOrEmpty(firstStr));
		Console.WriteLine("secondStr "+String.IsNullOrEmpty(secondStr));
		Console.WriteLine("thirdStr "+String.IsNullOrEmpty(thirdStr));
		Console.WriteLine("fourthStr "+String.IsNullOrEmpty(fourthStr));
		Console.WriteLine("fifthStr "+String.IsNullOrEmpty(fifthStr));
	}
}

It will print the below output:

firstStr True
secondStr False
thirdStr False
fourthStr True
fifthStr True

You might also like: