Monday, March 16, 2015

String Extension to use instead of String.IsNullOrEmpty

Everyday while writing C# code until C# 6.0 comes I have to write code like this many times.

var firstName ="";
if(String.IsNullOrEmpty(firstName)){
"firstname is null or empty".Dump();
}

So one might ask what is wrong with this code. Nothing but it is not quite intuitive and readable. When you read, it doesn’t sound appropriate. I think that if(firstName.IsNullOrEmpty()) reads better and one doesn’t have to think of calling a static function.

public static class StringExtension
{
public static bool IsNullOrEmpty(this string value)
{
return String.IsNullOrEmpty(value);
}
public static bool IsNullOrWhitespace(this string value)
{
return String.IsNullOrWhiteSpace(value);
}
}
This allows us following.
if(firstName.IsNullOrEmpty())
{
"This reads much better.".Dump();
}

No comments:

Post a Comment