Dynamic anonymous types

04/26/10

Dynamic anonymous types

In C# 4.0, you can return anonymous types from methods by using the dynamic keyword.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(GetHello().Name);  // Works.

        var one = GetHello();
        var two = GetHello();

        if (one.Equals(two))
        {
            Console.WriteLine("They are equal!");
            // Hit - they are equal!
        }
        else
        {
            Console.WriteLine("They are NOT equal.");
        }
    }

    static dynamic GetHello()
    {
        return new { Name = "Bob" };
    }
}

Note that Equals still works as expected.

I think this will make it possible to refactor long LINQ statements that use anonymous types, breaking them up into calls to private methods. (Clearly this could be abused as well.)

Update - December 11, 2011

There’s some protection against abuse - anonymous types are internal. Thanks to Marc Gravell for pointing this out.


Your Host: webmaster@truewill.net
Copyright © 2000-2013 by William Sorensen. All rights reserved.