OneBite.Dev - Coding blog in a bite size

Check If A String Is Empty In C#

Code snippet for how to Check If A String Is Empty In C# with sample and detail explanation

Just as it is crucial to check user inputs in a software application, it is also necessary to verify whether a string is empty or not in any given C# program. This article will walk you through how to efficiently check if a string is empty in C# by providing a code snippet and an explanation of how it works.

Code Snippet: Checking if a String is Empty in C#

string str = "";

if(String.IsNullOrEmpty(str))
{
    Console.WriteLine("String is empty");
}
else
{
    Console.WriteLine("String is not empty");
}

Code Explanation for Checking if a String is Empty in C#

Our given C# code snippet revolves around the built-in IsNullOrEmpty method, which can be invoked to determine whether a specific string is either null or an Empty string.

Initially, we declare a string variable str and initialize it with an empty string ("").

Then, we use an if statement that utilizes the String.IsNullOrEmpty method. This method receives our string variable str as its argument and performs a check.

In this case, IsNullOrEmpty will return true if the string is null or if it just contains whitespace characters, i.e., it is an empty string. If it is true, it means our string is empty, and the program will print “String is empty” to the console.

If the IsNullOrEmpty method returns false, it signifies that the string is not empty and has some content. The program, therefore, enters the else branch of the if statement and prints “String is not empty” to the console.

You can replace the initial str value with any string you’d like to check. This way, you can effectively utilize this code snippet as a tool to establish whether any given string in your C# project is empty.

c-sharp