Accessing C# Anonymous Type Objects

How do i access objects of an anonymous type outside the scope where its declared?

for e.g.

void FuncB()
{
var obj = FuncA();
Console.WriteLine(obj.Name);
}

??? FuncA()
{
var a = (from e in DB.Entities
where e.Id == 1
select new {Id = e.Id, Name = e.Name}).FirstOrDefault();

return a;
}

As the other answers have stated, you really shouldn't do this. But, if you insist, then there's a nasty hack known as "cast by example" which will allow you to do it. The technique is mentioned in a couple of articles, here and here.

public void FuncB()
{
    var example = new { Id = 0, Name = string.Empty };

    var obj = CastByExample(FuncA(), example);
    Console.WriteLine(obj.Name);
}

private object FuncA()
{
    var a = from e in DB.Entities
            where e.Id == 1
            select new { Id = e.Id, Name = e.Name };

    return a.FirstOrDefault();
}

private T CastByExample<T>(object target, T example)
{
    return (T)target;
}

(I can't take the credit for this hack, although the author of one of those articles says that he doesn't want to be associated with it either. His name might be familiar.)


You can't return an anonymous type from a function.

From the MSDN documentation:

To pass an anonymous type, or a collection that contains anonymous types, outside a method boundary, you must first cast the type to object. However, this defeats the strong typing of the anonymous type. If you must store your query results or pass them outside the method boundary, consider using an ordinary named struct or class instead of an anonymous type.


If you are using .NET 4.0, you can use Tuples for this, you'd return a Tuple<int, string>. You can implement your own Tuples for 2.0/3.5, and actually other people already have, so you should be able to do that if you like.