C# Improving string.IsNullOrEmpty readability

C

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:

[code]
if (!string.IsNullOrEmpty(myString)) {
// Do something
}
[/code]

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:

[code]
public static class StringExtensions
{
public static bool HasValue(this string value)
{
return !string.IsNullOrEmpty(value);
}
}
[/code]

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

[code]
if (myString.HasValue()) {
// Do something
}
[/code]

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.

Other useful articles

About the author

By Jamie

My Books