End Your If

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. 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.
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
blog comments powered by Disqus