Another alternative to solve this problem (depending on your circumstances) is to leverage Newtonsoft.Json's ExpandoObjectConverter
JSON converter class.
Serialize your object to JSON, then deserialize it as an ExpandoObject
into a dynamic
field using the converter:
Person person = new Person("Sam", "Lewis");
var personJson = JsonConvert.SerializeObject(person);
dynamic personExpando =
JsonConvert.DeserializeObject<ExpandoObject>(personJson, new ExpandoObjectConverter());
personExpando.Dob = "1/1/1900";
personExpando.Address = "777 Pearly Gates Dr.";
The new object you end up with will have the properties just as you've added them:
{
"FirstName": "Sam",
"LastName": "Lewis",
"Dob": "1/1/1900",
"Address": "777 Pearly Gates Dr."
}
Do note, however, that the original person
object is unchanged; we didn't actually mutate that object at all.
The normal caveats for JSON serialization apply, so your mileage may vary, but if your fields are properly serializable and your object isn't deeply nested, this should present no problems.
As an aside, you should absolutely expand or create a suitable contract for your object's fields instead of using this in basically all cases. It will be more robust, more maintainable, and will save you from bugs and type-related errors that can come with workarounds.
That said, sometimes things aren't so neat, so having an escape hatch like this can be useful for exceptional situations– just don't use it without due cause.