I'm trying to initialize objects in a C# program in a way such that both the properties and values are only known at runtime. I'm using a nuget package which requires the class definition to be known in order for it to function properly, and I'm trying to programmatically create this class.
Based on this post I just found, it looks like using ExpandoObject is a step in the right direction since we can set the properties at runtime, however these properties are still known a priori and hard-coded into the program. What I want to be able to achieve is having a list of arbitrarily many properties ["a", "b", "c", "d", "e", ...] and be able to set them as properties in a newly instantiated object as follows:
class Program
{
static void Main(string[] args)
{
dynamic chano = new ExpandoObject();
string test = "a";
chano[test] = "Free the Carter, people need the Carter";
Console.WriteLine(chano[test]); //want to console "Free the Carter...", of course this fails in compilation
Console.ReadKey();
}
}
However, of course we run into the issue that we can't index objects using []. Are there any analogous dynamic object types that will allow me to achieve the functionality I'm looking for?