Access to 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 property a 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 them.

+6
source share
2 answers

If you cannot use static typing for your anonymous class, you can use dynamic , for example:

 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 disadvantage of this approach is that the compiler will not help you detect situations when a property is not defined. For example, you can write this

 Console.WriteLine("{0} {1}", test.abc, test.xyz); // <<== Runtime error 

and it will compile, but it will crash at runtime.

+2
source

If you need compiler support, you should use var , not object . He must admit that you have an object with properties a and b . In the above code, you are omitting object , 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 can’t use var for any reason, you can look into dynamic or this cumbersome hack to pass anonymous types from Skeet

+6
source

Source: https://habr.com/ru/post/959486/


All Articles