Thursday 18 December 2014

A note about .net extension methods

If you've ever programmed in C#, you've probably encountered this one awesome feature called extension methods that allows you to add new methods to existing types without modifying the original type (in reality, this feature is nothing more than syntactic sugar for invoking utility methods in a natural object-oriented manner. Still, being able to call utility methods in such a manner is much better and is partly the reason why the various LINQ APIs are so elegant to use)

One thing that people may overlook when writing their extension methods is the namespace in which the extension method class is defined in.

Simply put, if you are going to write extensions methods for a class/interface/enum, you should define the extension method class in the same namespace as the class/interface/enum that you are "extending"

The reason for this is simple: It improves discover-ability of these extension methods. Any time you bring in a namespace for a given class/interface/enum, the extension methods (being in the same namespace) will also be brought in automatically.

If these extension methods were in a different namespace, you'd have to manually seek out the namespace where these extension methods live in, which ranges from inconvenient to annoying. I've had to ILSpy many assemblies in my time just to find the proper namespace of this one extension method that the documentation keeps referring to, all because the extension methods lived in a separate namespace from the "extendee" class/interface/enum.

Something to think about before you write your next extension method.