3

I need to create dynamic object and its properties at run-time then create instance of this object to store values.

why I want above logic!

I am reading excel file in C# and first line of code is header which is actually properties and followed by each rows are record which is instance of 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 in object

3
  • 1
    Usually you set the proerties by using MyDynamic.PropertyName = value. In your case value probably comes from the sheet, so it´s rather something like MyDynamic.PropertyName = ExcelDataHeader[3]. I don´t understand what your question is. Commented Apr 7, 2017 at 10:52
  • Possible duplicate of Dynamically Add C# Properties at Runtime Commented Apr 7, 2017 at 10:54
  • 1
    Why create a dynamic object? Just store your values in a Dictionary. Seems a lot simpler to me. Commented Apr 7, 2017 at 10:55

1 Answer 1

2

You could use ExpandoObject here - it'll work, but you need to use the dictionary API:

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 fail to see the point. Since you won't be referring to the object in C# code by things like obj.PropertyName, dynamic has very little purpose. You might as well just store each record in a Dictionary<string,object> or similar. Given what you describe, there are no places where you would actually use MyDynamic as a dynamic object.

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.