How many times have you wanted to check a value type such as an integer for nulls or zeros with ease. Previously you would've had to write something like the following:
Note: the ? indicates a nullable generic.
int? i = 0;
if (i == null || i == 0)
//Do something
The above code is fine, but we can simplify it.
Here's a simple example of its use:
1. Define a static class, the name doesn't really matter but the class must be static.
public static class IntHelper
{
}
2. Now implement a new method as follows:
public static class IntHelper
{
public static bool IsNullOrZero(this int? i)
{
if (i == null || i == 0)
return true;
else
return false;
}
}
The method must also be static and contain the this keyword before the type.
3. Now in order to use this extension, we could code something like the following:
int? i = null;
if (i.IsNullOrZero())
Console.WriteLine("i is null");
The above code is alot cleaner than testing for zeros and nulls. Of course you could let your imagine run wild with extension methods. But I recommend only using them for simple operations as your code could soon become too complicated which would then become more difficult to maintain especially when new developers come on board.
No comments:
Post a Comment