0

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?

Community
  • 1
  • 1
Adam Freymiller
  • 1,929
  • 7
  • 27
  • 49
  • 1
    Maybe you're looking for a `Dictionary`? – René Vogt Aug 05 '16 at 15:25
  • The reason I would like to programmatically define a class is because I'm using a CsvHelper nuget package which requires the dev to have defined a class which corresponds to all row entries in the ingested csv file. http://stackoverflow.com/questions/7595416/convert-dictionarystring-object-to-anonymous-object looks like a promising means to get from a dictionary to an object, but I think I need to programmatically define a class – Adam Freymiller Aug 05 '16 at 15:31
  • So, your *actual* problem is how to read dynamic objects from CsvHelper, and you though that you have to create a dynamic object in advance, using the dynamic feature as if it were a dictionary. That's the definition of the XY problem, having problem X but asking about an attempted solution Y. The actual question is "How do I load dynamic objects from CsvHelper" ? – Panagiotis Kanavos Aug 05 '16 at 15:43
  • @PanagiotisKanavos that is very probable, I will do a little bit more research and check your answer before changing the title just to be safe – Adam Freymiller Aug 05 '16 at 15:48

1 Answers1

2

The real question from the comments appears to be "How can I load rows dynamicallly using CsvHelper"? Dynamic support was added in version 2.0 a few years ago. You can return dynamic objects by passing dynamic as the type, ie:

dynamic records=csv.GetRecords<dynamic>();
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236