Monday, July 18, 2011

IsDefault extension

Known reserved word of C#  default(TYPE)  can be used as very usability feature as IsDefault():

public static bool IsDefault<T>(this T value)
{
    return value == null || value.Equals(default(T));
}
A can be available in every place in the project by next using:

int number = 5;
if (number.IsDefault())
{
    //...
}

It's  short and simple alternative to usual:
if (number == default(int)) 

The extension work nice with objects:
class Foo
{
    public int Id { get; set; }
    public int Name { get; set; }
}
//...
Foo foo = new Foo();
if (!foo.IsDefault())
{
    //....
    foo.Name = "John Smith";
}
 Enjoy!

No comments:

Post a Comment