object o = new { foo = 1 };
Is there any other way to add properties to the object?
Neither o["foo"] = 1 nor o.foo = 1 seems to be working.
And if i type
var o = new { foo = 1 };
Why is the type of var an “AnonomuysType” and not object?
You can’t just add properties to compiled types. The only time that will work as properties (well, kind-of) is if you are using the
dynamicAPI, and the object is something that supports dynamic properties, for example:however, those values are not available via reflection. An easier approach may be something that behaves as a dictionary:
there are more discoverable, via the dictionary API. Re your final question: when you do:
the
new { foo = 1 }causes the compiler to generate an anonymous type, which is a regular C# class with read-only properties and an unpronounceable name. This can be referred to asobject(it is a regularclass, after all), but when you usevarthe compiler uses the known type (with the horrible name), which gives you access to the properties (.fooin this case).