Friday 13 January 2012

Interfaces on Anonymous function revisted in C#

Last year I wrote a blog about adding interfaces to anonymous functions in Python. Since then I have being programming in .Net (C# and VB.Net) and was curious to see how easy it would be to achieve something similar in C#. I'm not using any IoC frameworks in C# so I wrote a very stupid one just for testing.

C# differs in a few key areas. You can't modify an object’s properties at runtime in C# without doing some Assembly hacking and even if you could, you can't add interfaces to anonymous or lamdba functions. So adding an interface and then adapting a runtime object based on its interfaces isn’t possible, so I ended up having to pass both interfaces around at all points (not ideal). The other major difference is that C# requires strict typing of the anonymous function so you can see 2 explicit casts in the code.

This isn’t the correct way of achieving this in C# but I found the contrast of coding something Pythonic in a different language interesting.





public interface IConcreteInterface { }
public interface ILambdaExpression { }

public class AdapterManager
{
protected readonly List<Adapter> services = new List<Adapter>();

public void registerAdapter<T, U>(object val)
{
var adapter = new Adapter() {
adapts = typeof(U),
implements = typeof(T),
val = val
};
services.Add(adapter);
}

public object resolve<T, U>()
{
return (from x in services where x.adapts == typeof(U) && x.implements == typeof(T) select x.val).Single();
}
}

var gsm = new AdapterManager();
gsm.registerAdapter<IConcreteInterface, ILambdaExpression1>((Func<string>)(() => "Hello World"));

var adapted = gsm.resolve<IConcreteInterface, ILambdaExpression1>();
var lambdaExp = (Func<string>)result
var result = lambdaExp();