Code4IT

The place for .NET enthusiasts, Azure lovers, and backend developers

How to check if a string is really empty with C#

2018-10-01 3 min read Blog

Is a string empty? What if it contains only white spaces? You shouldn’t reinvent the wheel, since .NET exposes methods exactly for these cases: String.IsNullOrEmpty and String.IsNullOrWhiteSpace.

Table of Contents

Just a second! 🫷
If you are here, it means that you are a software developer. So, you know that storage, networking, and domain management have a cost .

If you want to support this blog, please ensure that you have disabled the adblocker for this site. I configured Google AdSense to show as few ADS as possible - I don't want to bother you with lots of ads, but I still need to add some to pay for the resources for my site.

Thank you for your understanding.
- Davide

To be, or not to be (empty), that is the question…

That’s a simple, yet complex, question.

First of all, when a string is not empty? For me, when there is at least one character or one number.

Do it from scratch

Let’s create a custom function to achieve this functionality.

public static bool IsStringEmpty(string myString){
// do something
}

Ok, now we have to think of how to check if the string myString is empty.

Of course, the string must be not null. And must not be empty. Maybe… its length must be greater than zero?

public static bool IsStringEmpty(string myString){

return myString==null || myString == String.Empty || myString.Length == 0;
}

Ok, we should be fine. But, what if the string contains only whitespaces?

I mean, the string " ", passed to the IsStringEmpty method, will return true.

If that’s not what we want, we should include this check on the method.
Of course, this implies a bit of complexity to check null values.

public static bool IsStringEmpty(string myString){

return myString==null || myString == String.Empty || myString.Length == 0 || myString.Trim().Length == 0 ;
}

Ok, we covered the most important scenarios.

So we can try the method with our values:

using System;
using System.Collections.Generic;

public class Program
{
	public static void Main()
	{
		var arr = new List() {"1", null, "   ", String.Empty, "hello"};
		foreach (string txt in arr)
		{
			Console.WriteLine("IsStringEmpty? " + IsStringEmpty(txt));
		}
	}

	public static bool IsStringEmpty(string myString)
	{
		if (myString == null)
			return true;
		myString = myString.Trim();
		return myString == String.Empty || myString.Length == 0;
	}
}

will return

IsStringEmpty? False
IsStringEmpty? True
IsStringEmpty? True
IsStringEmpty? True
IsStringEmpty? False

Fine. Too tricky, isn’t it? And we just reinvented the wheel.

.NET native methods: String.IsNullOrEmpty and String.IsNullOrWhitespace

C# provides two methods to achieve this result, String.IsNullOrEmpty and String.IsNullOrWhiteSpace, with a subtle difference.

String.IsNullOrEmpty checks only if the string passed as parameter has at least one symbol, so it doesn’t recognize strings composed by empty characters.

String.IsNullOrWhitespace covers the scenario described in this post. It checks both empty characters and for escape characters.

string str1 = "hello";
Console.WriteLine(String.IsNullOrEmpty(str1)); //False
Console.WriteLine(String.IsNullOrWhiteSpace(str1)); //False

string str2 = null;
Console.WriteLine(String.IsNullOrEmpty(str2)); //True
Console.WriteLine(String.IsNullOrWhiteSpace(str2)); //True

string str3 = "";
Console.WriteLine(String.IsNullOrEmpty(str3)); //True
Console.WriteLine(String.IsNullOrWhiteSpace(str3)); //True

string str4 = "\n   \t   ";
Console.WriteLine(String.IsNullOrEmpty(str4)); //False
Console.WriteLine(String.IsNullOrWhiteSpace(str4)); //True

string str5 = "       ";
Console.WriteLine(String.IsNullOrEmpty(str5)); //False
Console.WriteLine(String.IsNullOrWhiteSpace(str5)); //True

You can see a live example here.

This article first appeared on Code4IT

Wrapping up

As you can see, out of the box .NET provides easy methods to handle your strings. You shouldn’t reinvent the wheel when everything is already done.

About the author

Davide Bellone is a Principal Backend Developer with more than 10 years of professional experience with Microsoft platforms and frameworks.

He loves learning new things and sharing these learnings with others: that’s why he writes on this blog and is involved as speaker at tech conferences.

He's a Microsoft MVP πŸ†, conference speaker (here's his Sessionize Profile) and content creator on LinkedIn.