I wondered how it might be possible to add members to a class “on the fly” and came up with this sample:
using System;
using System.Collections.Generic;
using System.Dynamic;
class Program
{
static void Main()
{
dynamic expando = new ExpandoObject();
var p = expando as IDictionary<String, object>;
p["A"] = "New val 1";
p["B"] = "New val 2";
Console.WriteLine(expando.A);
Console.WriteLine(expando.B);
}
}
The point of this code snippet is that the members A and B are defined as string literals (hard coded/stringified) in and added via ExpandoObject’s IDictionary interface. We test for the keys’ existence and values (and prove the concept) by accessing them directly and outputting to console.