Wednesday, May 14, 2008

Anonymous Interface Implementation

With the introduction of lambdas, it's now incredibly easy to pass tiny bits of functionality around. Unfortunately, some existing methods in the Framework take parameters of an interface type, instead of a delegate. Contains, for example, takes an IEqualityComparer instead of a Predicate. This makes using these methods in an ad-hoc manner difficult. What we need is the ability to quickly throw together a temporary class that implements the interface, basically an anonymous type only with method implementation.

I submitted a Connect item about this (here), but as you can see it won't be making it into this release.

To tide myself over I wrote a version that is built on anonymous types, Reflection.Emit, and Funcs. You can download it here. This is a proof of concept...no warranties...don't use in production...blah blah blah.

As a sample, here's how to create an instance of IEqualityComparer that thinks strings are equal if they are the same length:

Make.Instance<IEqualityComparer<string>>(
new {
Equals = Make.Func(
(string x, string y) => x.Length == y.Length)
})


I had to use Eric Lippert's trick to get lambdas and inferencing working in anonymous types.