Dynamic anonymous types

04/26/10

Permalink 06:49:37 pm, by truewill Email , 119 words, 225 views   English (US)
Categories: C#, .NET

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.

Comments, Pingbacks:

No Comments/Pingbacks for this post yet...

Leave a comment:

Your email address will not be displayed on this site.
Your URL will be displayed.

Allowed XHTML tags: <p, ul, ol, li, dl, dt, dd, address, blockquote, ins, del, span, bdo, br, em, strong, dfn, code, samp, kdb, var, cite, abbr, acronym, q, sub, sup, tt, i, b, big, small>
(Line breaks become <br />)
(Set cookies for name, email and url)
(Allow users to contact you through a message form (your email will NOT be displayed.))
The name truewill is composed of two other words. What is the SECOND word?

Development Central

Development Central is the blog of Bill Sorensen, a professional software developer. Much of this will relate to C#, .NET, and OOP in general.

Disclaimer
These postings are provided "AS IS" with no warranties and confer no rights.

Search

Categories

Linkblog

b2evolution

contributors

XML Feeds

What is RSS?

Who's Online?

  • Guest Users: 4

powered by b2evolution free blog software