cover-img

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

24 September, 2021

5

5

1

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.
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?
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.
Ok, we covered the most important scenarios.
So we can try the method with our values:
will return
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.
You can see a live example here.

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.

csharp

dotnet

5

5

1

csharp

dotnet

Davide Bellone
Let's talk about .NET, Azure and Clean code, shall we? Ah, I'm learning Software Architecture.

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2024. Showcase Creators Inc. All rights reserved.