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.