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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With