Create an object and its properties at runtime from a list

I need to create a dynamic object and its properties at runtime and then instantiate that object to store the values.

why i want above logic!

I am reading an excel file in C # and the first line of code is the header, which is actually a property, followed by the records, which are an instance of a dynamic object.

 List<string> ExcelDataHeader = new List<string>();
         for (int y = 2; y <= colCount; y++)
           {
             ExcelDataHeader.Add(xlRange.Cells[headerRow, y].Value2.ToString());
           }

  dynamic MyDynamic = new System.Dynamic.ExpandoObject();
    ??????????

      

I need to return excel read data to object

+3


source to share


1 answer


You can use here ExpandoObject

- it will work, but you need to use the API dictionary:

IDictionary<string, object> obj = new ExpandoObject();
obj["id"] = 123;
obj["name"] = "Fred";

// this is the "dynamic" bit:
dynamic dyn = obj;
int id = dyn.id; // 123
string name = dyn.name; // "Fred"

      



However, I don't see the point. Since you won't be referring to an object in C # code with things like obj.PropertyName

, dynamic

has very little purpose. You can just save each entry in Dictionary<string,object>

or similar. Given what you've described, there are no places where you would actually use it MyDynamic

as an object dynamic

.

+2


source







All Articles