I have a class as shown below.
public class MyClass
{
public DateTime Date
{ get; set;}
public double Col1
{ get; set;}
public double Col2
{ get; set;}
public double Col3
{ get; set;}
And I have a list of values in the
Dictionary<string, double> Items
Items["AA", 23.56] // these AA, BB values will change.
Items["BB", 15.456] etc
and I want to set the value of properties of the MyClass. Is this possible as shown below:
MyClass obj = new MyClass();
int i = 0;
foreach (KeyValuePair<string, double> entry in items)
{
// take the first property (Col1) and assign the value.
obj[i] = entry.value; // is this possible
i++;
}
OR
Here I am iterating through the class properties using reflection and find each value from the Dictionary then assign it to the Myclass property.
MyClass obj = new MyClass();
PropertyInfo[] properties = typeof(MyClass).GetProperties();
foreach (PropertyInfo property in properties)
{
var value = // take the value from Dictionary.
property.SetValue(obj, value);
}
The aim of the question is to set the value of MyClass's properties at run time. I dont know how many items will be present in the Dictionary in advance. Finally it will be like,
MyClass obj = new MyClass();
obj.Col1 = 23.56 // value of AA
obj.Col2 = 15.456 // value of BB
obj.Col3 = 100.23 // value of CC...it goes like this.
Is this possible? If yes, how?