Reputation: 10056
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.
Upvotes: 6
Views: 394
Reputation: 67065
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
Upvotes: 6
Reputation: 726479
If you cannot use static typing for your anonymous class, you can use dynamic
, like this:
static object MakeAnonymous() {
return new {a = "3", b = "4"};
}
static void Main(string[] args) {
dynamic test = MakeAnonymous();
Console.WriteLine("{0} {1}", test.a, test.b);
}
The downside to this approach is that the compiler is not going to help you detect situations when a property is not defined. For example, you could write this
Console.WriteLine("{0} {1}", test.abc, test.xyz); // <<== Runtime error
and it would compile, but it would crash at runtime.
Upvotes: 2