Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 512
Ali Kazmi Avatar asked Apr 03 '09 11:04

Ali Kazmi


People also ask

What is C$ share in Windows?

C$ and x$ - The default drive share, by default C$ is always enabled. The x$ represents other disks or volumes that are also shared, e.g., D$, E$, etc. FAX$ - Share used by fax clients to access cover pages and other files on a file server.


1 Answers

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.)

like image 188
LukeH Avatar answered Sep 23 '22 00:09

LukeH