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);
and it will compile, but it will crash at runtime.
source share