I have a class called CoverageBase with properties say A, B, C. And now based on some checks i need to append n number of properties say D and E properties in to this CoverageBase class along with my existing A, B, C. So for creating D and E dynamically during the runtime i am using Dictionary
class CoverageBase
{
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
}
Dictionary<string, object> values = new Dictionary<string, object>()
{
{"D",5},{"E",123}
};
var test = GetObject<CoverageBase>(values);
T GetObject<T>(Dictionary<string,object> dict)
{
Type type = typeof(T);
var obj = Activator.CreateInstance(type);
foreach (var kv in dict)
{
type.GetProperty(kv.Key).SetValue(obj, kv.Value);
}
return (T)obj;
}
The problem with above approach is, when i try to GetProperty using "D" there will not be any property existing in that name in the CoverageBase class right. so it will throw error. So how do i build my expected class with properties A, B, C, D, E
Can we use any of the existing tools like ExpandoObject or DynamicObject for this?