I'm trying to create a dynamic list of objects because I don't know what properties my objects will have until I read them from a file.
So suppose I have the properties of my object inside an array (e.g. FirstName, LastName,Email).
I want to create dynamic objects called Recipient with the above properties. Then I want to create a list and add some of these objects to that list.
I have done the following so far but I'm not sure if this is correct way of assigning properties to a dynamic object ("fields" is the name of the array):
var persons = new List<dynamic>();
dynamic Recipient = new ExpandoObject() as IDictionary<string, Object>;
foreach (string property in fields)
{
Recipient.property = string.Empty;
}
How do I create a recipient object with the properties mentioned above and then add those recipients to the persons list?
ExpandoObject
implements the IDictionary<string, object>
interface, where the key/values would be mapped to the the member name/values. If you have the property names in the fields
array, you'd just use those as the dictionary keys:
IDictionary<string, object> recipient = new ExpandoObject();
foreach (string property in fields)
{
recipient[property] = string.Empty;
}