11

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?

disasterkid
  • 6,948
  • 25
  • 94
  • 179

1 Answers1

15

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;
}
Eren Ersönmez
  • 38,383
  • 7
  • 71
  • 92
  • so far so good. now please tell me how do I print recipient's properties in the console once these properties are assigned. – disasterkid Jan 07 '13 at 16:05
  • that means looping through recipient's properties in order to get e.g. FirstName, LastName,Email on the screen because I need these properties to create my objects with. – disasterkid Jan 07 '13 at 16:07
  • 1
    @Pedram since you only know the property names at runtime, yes, you need to enumerate it as a dictionary to get the name/values. – Eren Ersönmez Jan 07 '13 at 16:15
  • 1
    `foreach(var kv in (IDictionary)recipient) Console.WriteLine("Key:{0} Value:{1}", kv.Key, kv.Value);` – Eren Ersönmez Jan 07 '13 at 16:34