Wednesday, June 20, 2007

Extension methods and Collection<T>

Visual Studio Code Analysis / FxCop says in rule CA1002 not to expose List<T> but instead something like Collection<T>.

Now List<T> has some nice features such as

List<T> List<T>.FindAll(Predicate<T> match) 

among others, not to mention

void List<T>.AddRange(IEnumerable<T> collection)

Now, we could go implementing these on our own base class and return that, or go back to C style object orientation and write a static CollectionUtilities class with methods such as

static void AddRange<T>(ICollection<T> collection, IEnumerable<T> items)

Neither of these makes me really happy.

Enter C# 3.0 extension methods:

public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> items)

{ /* implementation */ }

Now due to some compiler magic we can use this method just as it had beed implemented directly in Collection<T>... Neat!

Another interesting tidbit is that it is in fact possible to do things like

            Thing foo = null;
if (foo.IsNull())
Console.WriteLine("foo is null!");

and NOT get a NullReferenceException due to an extension method along the lines of:

        public static bool IsNull(this object value)
return value == null;

unfortunately, as they are called extension methods it's only possible for methods and not properties and such.

No comments: