Adding Implementation to Interfaces with Extension Methods

by jmorris 21. January 2011 22:58

One of the quirks of extension methods added to the .NET 3.5 release is that you can add them to interfaces;  seemingly adding implementation to interfaces. By definition, in the CLR (and most other languages or platforms) interfaces contain only the signatures of methods, delegates, properties or indexers. By implementing an interface in a class, the body of the method, delegate, property or indexer is added…the implementation is added.

For example:


Here I am extending the IMessage interface with a couple of methods for simplifying access to value pairs contained within a IPrimitiveMap (a hash map implementation).  A couple of unit tests illustrates the usage:


Truthfully, you are truly adding nothing the interface! No implementation is actually added…basically a static class is created with the extension methods and some compile time kung fu enables you to invoke the method off of the interface definition. Extension methods are not of the domain of the CLR, they are of the domain of the compiler via the System.Runtime.CompilerServices.ExtensionAttribute.

I would imagine this is old news for most seasoned .NET developers, but I just kind of stumbled upon it myself today and thought it was interesting with respect to interfaces and implementation :)

Tags: ,


Comments (2) -

Steve Gentile
Steve Gentile
3/3/2011 2:59:34 AM #

Interesting - I didn't realize this was possible either!


Android RPG
Android RPG
9/3/2011 9:12:46 AM #

Me being a .NET newbie, this isn OLD news Smile

Jeff Morris

Tag cloud

Month List

Page List