Extension Methods
Aug 25 2008 10:43 PM Filed in: .NET
Since we are using Silverlight on this new project I
am working on, we are doing our development in .NET
3.5. One of the new features in .NET 3.5 is Extension
Methods. When I first saw this I figured it was a
nice feature, but I didn’t know when I would use it.
Today I wrote a couple. I figure there’s probably a
couple reasons you would create an Extension Method:
(a) You see you are performing the same coding
routine in multiple places, and it would be nice if
you could replace it with less code, and (b) there’s
a method you always wished was on one of the built in
.NET types -- something like String.ToUpperCase() or
something along those lines. The Extension Methods I
wrote today fell into the first category. We have a
lot of places in our code where we check if an object
is null before progressing.
I wrote a simple IsNull Extension Method that can be applied to any object as long as a reference to my Extension Method namespace is in the using directives.
It’s very simple, and only saves a little typing, but it looks nicer to have the following
We also tend to have a lot of code that checks if a List is not null and also isn’t empty
For this I created an IsNullOrEmpty Extension Method
This way you can write the code as
These are the only Extension Methods I’ve written so far, but I can think of another one that would be useful and would fall into the second category of why you would write Extension Methods. Let’s say the Generic List of Integer TitleIds I had in the previous example had a couple duplicates, it would be nice to be able to say
if (contract == null)
return;
I wrote a simple IsNull Extension Method that can be applied to any object as long as a reference to my Extension Method namespace is in the using directives.
public static bool IsNull(this object source)
{
return source == null;
}
It’s very simple, and only saves a little typing, but it looks nicer to have the following
if (contract.IsNull())
return;
We also tend to have a lot of code that checks if a List is not null and also isn’t empty
if (titleIds == null || titleIds.Count == 0)
return;
For this I created an IsNullOrEmpty Extension Method
public static bool IsNullOrEmpty<T>(this
List<T> source)
{
return ((source == null) ||
(source.Count == 0));
}
This way you can write the code as
if (titleIds.IsNullOrEmpty())
return;
These are the only Extension Methods I’ve written so far, but I can think of another one that would be useful and would fall into the second category of why you would write Extension Methods. Let’s say the Generic List of Integer TitleIds I had in the previous example had a couple duplicates, it would be nice to be able to say
titleIds.RemoveDuplicates();
|