C# Improving string.IsNullOrEmpty readability C# Improving string.IsNullOrEmpty readability

I often find myself using this great C# function: string.IsNullOrEmpty. It is the assured way to confirm whether a string is empty - null or otherwise. However, I often find myself wanting to know when it is not empty, so I wrote an string extension named HasValue.

Thus I have to write an if statement that reads more like this:

if (!string.IsNullOrEmpty(myString)) {
// Do something

I personally do not find this very readable because of the ! at the start of the if statement similar to how I like to organize my CASE Statement in SQL.

Creating a String Extension

Enter this little handy tidbit of code - a string extension - to improve readability:

public static class StringExtensions
public static bool HasValue(this string value)
return !string.IsNullOrEmpty(value);

Inside the function HasValue contains the same if condition defined above. Now however, I can use the string extension method as follows:

if (myString.HasValue()) {
// Do something

This of course matches the similar concept with nullable booleans or integers where they contain a built-in HasValue check.

Thought I'd share as I previously stated Developers are authors and this makes your code much more readable.

Published on Feb 5, 2019

Tags: ASP.NET MVC and Web API Tutorial | c# | string.isnullorempty | extensions

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.


Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.