Adding some dynamic to C#: interface wrapping

C# is not a dynamic language. That’s for sure! Recently, the adding of the var keyword, anonymous types and lambda expressions have added some “dynamic” to the language. But still it’s not a dynamic language.

I have heard people saying that C# is never going to be a dynamic language. But it seems as if the next version is going to add more dynamic to the language.

C# being completely static sometimes bothers me; it’s not that often but sometimes I would like to do something and it’s only possible with a lot of walk arounds and sometimes even minor hacks. One thing, for example, is that you can’t really return an instance of a anonymous type from a method without doing a little bit of weird looking hacking (greetings to Tomas; it was cool to chat with you in the metro at the end of TechEd).

Wouldn’t it be cool if an anonymous type could be wrapped into an interface and you could return that? Also, wouldn’t it be cool to wrap any type (also the one that are part of the .NET Framework) into an interface; independent of the type implementing that interface. Let’s say you have objects that implement a Close method and you want to define an interface called IClosable. Now if a class implements the Close method you want to wrap it into the IClosable interface and store all these instances in a Dictionary for later usage.

With C# you can’t do that because it’s not possible to cast an object to an interface if not implemented.

Still that feature would be interesting to have in some scenarios and that’s why I implemented a class that enables that. In enables you to wrap any class into an interface, when the class implements the methods and properties that are required by the interface. The class doesn’t need to implement the interface!

public interface IFoo
{
    string Name { get; }
    int Age { get; }
}

class Program
{
    static void Main(string[] args)
    {
        IFoo foo = CreateDynamicType();

        var name = foo.Name;
        var age = foo.Age;

        // output the results.
        Console.WriteLine(name + ” “ + age);
    }

    public static IFoo CreateDynamicType()
    {
        // create the anonymous type.
        var f = new { Name = “Test”, Age = 100 };

        // wrap the interface around the type.
        IFoo foo = f.WrapIntoInterface<IFoo>(false);
        if (foo == null)
            throw new Exception(“Houston, we’ve had a problem.”);

        return foo;
    }
}

The example shows the wrapping of an anonymous type into the IFoo interface.

Making this work involves a little bit of magic and some deeper knowledge of the CLR and IL. The .NET Framework offers in the System.Reflection.Emit namespaces classes that allow creating assemblies, modules, types, methods, properties etc. during runtime. I have used these classes to create the solution.

If the user wants to wrap a class with an interface a new in-memory class is generated and that new class implements the required interface. The generated class has also a constructor that takes the original class as argument. If one of the interface methods or properties are invoked the call is forwarded to the inner class.

The in-memory generated class for the example before looks like this:

// This class implements the IFoo interface and
// wraps the original instance.
public sealed class <>f__AnonymousType0`2<>IFoo__$wrapper$! : IFoo
{
    // The original instance.
    private <>f__AnonymousType0<string, int> _original;

    // The constructor takes the original instance.  In this case an
    // instance of the anonymous class.
    public <>f__AnonymousType0`2<>IFoo__$wrapper$!(
        <>f__AnonymousType0<string, int> type1)
    {
        this._original = type1;
    }

    // other methods, like Equals, ToString etc.; collapsed.

    // The property calls are forwarded to the original object.
    public override int Age
    {
        get { return this._original.Age; }
    }

    public override string Name
    {
        get { return this._original.Name; }
    }
}

I’m cheating a little bit under the covers by creating this dynamic class; C# hasn’t become dynamic from the sudden. But creating the in-memory class does the job very nicely and the user doesn’t see it.

To enhance speed I’m also adding the generated types to a dictionary. That increses speed because for further requests the type can be reused and doesn’t need to be generated again.

This approach could also be extended to enable aspect-oriented programming for C# or .NET in general. The idea would be to add call backs before and after the method/property/etc. calls are forwarded to the inner (wrapped) class.

Interesting in playing with this code? Click here to download the full source code (including the example of this post).

Published on Mar 21st, 2008 — Tags: , , ,
   digg it!    kick it   

6 Comments ( Comments RSS TrackBack )

  1. hey littleguru. have you taken a look at:

    LinFu - http://www.codeproject.com/script/Articles/MemberArticles.aspx?amid=101687

    and Ninject - http://ninject.org/

    seems like these would fit the bill nicely….

    Comment by David — March 25, 2008 @ 4:37 am

  2. Hey. I have seen it and it looks cool… I didn’t know about it when I started to do my little half-day project :D The framework looks really cool.

    Comment by Christian Liensberger — March 25, 2008 @ 8:24 pm

  3. What about:

    // Useful? probably not.
    private void foo()
    {
    var user = AnonCast(GetUserTuple(), new { Name = default(string), Badges = default(int) });
    Console.WriteLine(”Name: {0} Badges: {1}”, user.Name, user.Badges);
    }

    object GetUserTuple()
    {
    return new { Name = “dp”, Badges = 5 };
    }

    // Using the magic of Type Inference…
    static T AnonCast(object obj, T type)
    {
    return (T) obj;
    }

    Comment by Jair Cazarin — September 23, 2008 @ 12:27 pm

  4. hmmm… this looks also like a big hack to me.

    Comment by Christian Liensberger — September 25, 2008 @ 5:18 am

  5. Hi. Would it not be more efficient to create a single assembly in-memory rather than one per type?

    Comment by Nathan Alden — January 29, 2011 @ 9:32 am

  6. ?? ?? ???? ??? http://www.weizss.com/

    Comment by ???? ??? — September 17, 2013 @ 8:16 pm

Leave a comment

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> [code][/code] [code lang="csharp"][/code].