1
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?

Johan
  • 35,120
  • 54
  • 178
  • 293

2 Answers2

2

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 dynamic API, and the object is something that supports dynamic properties, for example:

dynamic obj = new ExpandoObject();
obj.Foo = 123;
obj.Bar = "abc";

however, those values are not available via reflection. An easier approach may be something that behaves as a dictionary:

var obj = new Dictionary<string,object>();
obj["Foo"] = 123;
obj["Bar"] = "abc";

there are more discoverable, via the dictionary API. Re your final question: when you do:

var o = new { foo = 1 };

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 as object (it is a regular class, after all), but when you use var the compiler uses the known type (with the horrible name), which gives you access to the properties (.foo in this case).

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

All objects inherit from Object even an anonymous type(see this question). You can see that here:

object o = new { foo = 1 };
if (o is object)
    Console.Write("Yes, i'm an object!");
else 
    Console.Write("no, no, i'm not an object!");

You cannot add properties to an anonymous type, only when you you create it.

You could use a Dictionary<string, object> instead:

var o = new Dictionary<string, object>();
o.Add("Foo", 123);
o.Add("Bar", "abc");

Now you can access them in this way:

object bar = o["Bar"]; // "abc"
Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939