//Any chance to cast this to the anonymous type?
Yes, you can use cast by example.
public static T CastByExample(this object obj, T example) {
return (T)obj;
}
Note that this only works if you're in the same assembly. Anonymous types have the same type if they are the same assembly, and the properties have the same names of the same type in the same order.
Then:
object b = Test();
var example = new { A = "example" };
var casted = b.CastByExample(example);
Console.WriteLine(casted.A);
Alternatively, you can use dynamic
:
dynamic b = Test();
Console.WriteLine(b.A);
Or, use reflection:
object b = Test();
var property = b.GetType().GetProperty("A");
var value = property.GetValue(b);
Console.WriteLine(value);
Or, you could just do the right thing and make a nominal (i.e., non-anonymous) type.