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.

1
2
3
4
5
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.

1
2
3
4
5
6
7
8
9
10
11
12
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.
1
2
3
4
5
if(firstName.IsNullOrEmpty())
{
      "This reads much better.".Dump();
}

No comments:

Post a Comment