Helping you solve those tough coding problems!

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

Published on Feb 5, 2019 by Jamie Munro

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.

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.

Tags: ASP.NET | c# | string.isnullorempty | extensions

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP