Archives for: April 2010

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.

Permalink 06:17:05 pm, by truewill Email , 18 words, 199 views   English (US)
Categories: Announcements [A], .NET, Conventions

News

Iowa Code Camp is coming up fast!

There’s also a new .NET group starting up in Iowa City.

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: 1

powered by b2evolution free blog software