Is it possible to create an extension method that returns the instance that is invoking the extension method?
I would like to have an extension method for anything that inherits from ICollection<T>, returns the object. Much like how jQuery always returns the jquery object.
public static object AddItem<T>(this ICollection<T> collection, T itemToAdd)
{
collection.Add(itemToAdd);
return collection;
{
I imagine something like above, but I am not sure how to get back to the parent to the “this” object type for use of something like this:
List<int> myInts = new List<int>().AddItem(5);
EDIT: Just wanted to be clear that i was hoping for a single generic constraint solution.
If you need to return the specific type, you can use a generic constraint:
I tested this and it works in VS2010.
Update (regarding jQuery):
jQuery chaining works very well because JavaScript uses dynamic typing. C# 4.0 supports
dynamic, so you can do this:However, I do recommend the generic constraint version, since it is more type-safe, more efficient, and allows IntelliSense on the returned type. In more complex scenarios, generic constraints aren’t always capable of expressing what you need; in those cases,
dynamiccan be used (though it won’t bind to additional extension methods, so it doesn’t work well with chaining).