C# in Depth

Cover of C# in Depth
Order now (3rd edition)

Extending the world... carefully

Chapter 10: Extension methods: 10.4.1

Created: 3/4/2008
Last updated: 3/4/2008

Eric has a bit of guidance about the use of extension methods:

Future versions of the frameworks design guidelines will probably say "please don't put extension methods on object, System.ValueType, System.Enum, unconstrained type parameters, etc."

We will violate this guideline ourselves in a few key places—a lot of people are asking for an In operator which is the inverse of Contains. static bool In<T>(this T, IEnumerable<T> ts) { ... } so you can say if 12.In(myints). A bit bogus if you ask me, but people like it. Clearly this would then be an extension method which matches every type.

There's one use of extension methods like this that has proved useful to me - acting on anonymous types, just by reflecting over their properties. I do this in chapter 12 with AsXAttributes and I've also got a version in MiscUtil for AsXElements.

I also have an extension method for any reference type, which throws an ArgumentNullException (with optional parameter name) is you call it on a null reference. This make argument checking easy - I just type foo.ThrowIfNull("foo");.