Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add an item to a object initialized with { blah = "asdf" }

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?

like image 348
Blankman Avatar asked Nov 29 '22 18:11

Blankman


1 Answers

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");
like image 144
BoltClock Avatar answered Dec 01 '22 07:12

BoltClock