Saturday, July 16, 2011

Extension method (3)

You may use extension method to increase the code readability too. For example, we often ensure that the object instance return by some function is not null before using.

CustomerClass customer = GetCustomerObject();

if (customer == null)
{
   // do this..
}
else
{
   // do that..
}

Wtih the extension method feature in C#, you may declare a new method call IsEmpty() which looks like this:

public static bool IsEmpty(this object obj)
{
  return (obj == null);
}

Now, you may do with your new IsEmpty() method:

CustomerClass customer = GetCustomerObject();

if (customer.IsEmpty())
{
   // do this..
}
else
{
   // do that..
}

Aside from improving the code readability, why we have to declare such IsEmpty() method instead of using "x == null"? This is what you are going to gain if you are using VS2010. When you type "." after the variable and follow by "Is", VS2010 will shortlist the methods that starts with "Is". Press Tab key to auto-complete the method name and you may move on to other code. This definitely will shorten the development time.

Note: you may rename this function to IsNull() or whatsoever.

No comments:

Post a Comment