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?

4
  • 1
    Maybe you're looking for a Dictionary<string,object>? Commented Aug 5, 2016 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. stackoverflow.com/questions/7595416/… looks like a promising means to get from a dictionary to an object, but I think I need to programmatically define a class Commented Aug 5, 2016 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" ? Commented Aug 5, 2016 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 Commented Aug 5, 2016 at 15:48

1 Answer 1

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>();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.