You seem to have 2 conflicting goals, and it comes down to what do you want your extension method to return:
- The instance that invoked the extension method (the collection)
- OR the item that was added to the collection
From your example usage, quoted here:
List<int> myInts = new List<int>().AddItem(5);
You make it look like you want to return the collection. In any case, that assignment still won't work without a cast, since your extension method would need to have a return type of ICollection, like this:
public static ICollection<T> AddItem<T>(this ICollection<T> collection, T itemToAdd)
{
collection.Add(itemToAdd);
return collection;
}
That would allow you to do this:
List<int> myList = (List<int>) new List<int>().AddItem(5);
Now if you'd rather return the object that was added, you still shouldn't have a return type of object
. You should take advantage of your generic type parameter, and return T
, like this:
public static T AddItem<T>(this ICollection<T> collection, T itemToAdd)
{
collection.Add(itemToAdd);
return itemToAdd;
}
However, if you're returning the item that was added, you won't be able to chain like this:
List<int> myList = (List<int>) new List<int>().AddItem(5);
, since the return type of AddItem(5)
is not ICollection, but it's T
(int
, in this case). You can still chain though, just off of the value added, like this:
List<int> myList = new List<int>();
myList.AddItem(5).DoSomethingWithMyInt(); // Not very useful in this case
It seems like the first scenario is more useful (returning the collection), because it does allow you chain, right off of the initial assignment statement. Here's a larger example of that:
List<int> myList = (List<int>) new List<int>().AddItem(1).AddItem(2);
Or, if you don't want to cast, you can call ToList()
on the ICollection that comes back:
List<int> myList = new List<int>().AddItem(1).AddItem(2).ToList();