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.
Iowa Code Camp is coming up fast!
There’s also a new .NET group starting up in Iowa City.
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.