Quantcast
Channel: Rantdriven - C#
Viewing all articles
Browse latest Browse all 4

Adding Implementation to Interfaces with Extension Methods

$
0
0

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:

image

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:

image

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 :)


Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles





Latest Images