Triggered by a recent blog posting by Andreas Finne, I’ll share a convenient extension method that I have written.
First, let’s give an introduction the “why” that triggered me writing this extension method from the beginning. The List<T> generic class is a pretty good class for keeping a list of objects (which are strongly typed, because this is a generic type). The List<T>, in turn, implements the ICollection<T> interface, which has a method defined which looks like this:
void Add(T item);
Now, there is only one big problem with this method: it should really return an ICollection<T>. Why, oh why didn’t Microsoft think of that? That way, you could have written your code like this:
IEnumerable<Customer> customers = new List<Customer>()
.Add(new Customer { CustomerNumber = 12345, Name = "Customer #1" })
.Add(new Customer { CustomerNumber = 23456, Name = "Customer #2" });
The problem withthis code snippet is that the Add() method returns void, which in turns means that the “fluid” syntax above is not possible.
Not until you work around it, that is.
The way we can solve this is by writing a generic extension method that works on an ICollection<T> object and does the Add() and then returns the collection itself. That way, we should be able to accommodate a similar syntax similar to this.
I prefer to place my extension methods in a class which is named “<class>ExtensionMethods”, where <class> is the name of the class which the extension methods operate on. Thus, I will call this class ICollectionTExtensionMethods. Here is the code:
public static class ICollectionTExtensionMethods
{
/// <summary>
/// Adds an item to the <see cref="System.Collections.Generic.ICollection<T>"/>.
/// </summary>
/// <typeparam name="T">The type of object which the collection contains</typeparam>
/// <param name="collection">The <see cref="System.Collections.Generic.ICollection<T>"/> to operate on</param>
/// <param name="item">The object to add to the <see cref="System.Collections.Generic.ICollection<T>"/></param>
/// <returns>The <see cref="System.Collections.Generic.ICollection<T>"/> we are operating on</returns>
public static ICollection<T> AddWithReturn<T>(this ICollection<T> collection, T item)
{
collection.Add(item);
return collection;
}
}
(I copied the XML documentation from the ICollection<T> interface definition metadata.
Now, we can write some code that looks like this: (Remember to include a using-line for the namespace where you placed this ICollectionTExtensionMethods class.)
IEnumerable<Customer> customers = new List<Customer>()
.AddWithReturn(new Customer { CustomerNumber = 12345, Name = "Customer #1" })
.AddWithReturn(new Customer { CustomerNumber = 23456, Name = "Customer #2" });
Pretty nice, huh?
Alright, this was it for this time. HTH!