Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing anonymous type variables

I have this code:

object test = new {a = "3", b = "4"};
Console.WriteLine(test); //I put a breakpoint here

How can I access a property of test object? When I put a breakpoint, visual studio can see the variables of this object... Why can't I? I really need to access those.

like image 828
ojek Avatar asked Dec 06 '13 15:12

ojek


People also ask

What are anonymous data types?

Anonymous types are class types that derive directly from object , and that cannot be cast to any type except object . The compiler provides a name for each anonymous type, although your application cannot access it.

What is the difference between an anonymous type and regular data type?

The compiler gives them a name although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object.

How do I return IQueryable anonymous type?

Just use IEnumerable/IQueryable as the return type and there is no need for ToList() at all. I like using tuples so from c# 7 you can simply return a tuple: IQueryable<(string Name, string BreedName)>, then in the linq query select (d.Name, b. BreedName). Then you don't need the multiple selects.


1 Answers

If you want the compiler support, then you should use a var and not object. It should recognize that you have an object with properties a and b. You are downcasting to an object in the above code, so the compiler will only have object properties

var test = new {a = "3", b = "4"};
Console.WriteLine(test.a); //I put a breakpoint here

If you cannot use var for whatever reason, then you can look into dynamic or this grotty hack for passing anonymous types from Skeet

like image 194
Justin Pihony Avatar answered Sep 28 '22 17:09

Justin Pihony