4

how to add an item to an object initialized with:

object obj = new { blah = "asdf" };

If I want to add another key value pair, how would i?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Blankman
  • 259,732
  • 324
  • 769
  • 1,199

3 Answers3

10

You can't modify the object's anonymous type definition once you make the object using that initializer syntax. That is, once you initialize it with { blah = "asdf" }, it only has that blah property. You can't add another. This is because anonymous types are static types.

The ExpandoObject answers work though, for a dynamic object. See the other answers for that.

If you're really just trying to manage a collection of key-value pairs (kinda sorta based on the way you phrased your question), use a dictionary.

var kvp = new Dictionary<string, string>
{
    { "blah", "asdf" }
};

kvp.Add("womp", "zxcv");
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
7

@BoltClock is right on. Another alternative is to use an ExpandoObject, at the loss of intellisense.

dynamic obj = new ExpandoObject();
obj.blah = "asdf";

// sometime later

obj.somethingelse = "dfgh";

// obj now has 'blah' and 'somethingelse' 'properties'
Tejs
  • 40,736
  • 10
  • 68
  • 86
6

Once you define an object like that, you're done. You can't add anything to it.

If you're using C# 4.0, though, you could always use a dynamic type:

dynamic obj = new ExpandoObject();

obj.blah = "asdf";
obj.blahBlah = "jkl;";
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536