12

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?

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

so far so good. now please tell me how do I print recipient's properties in the console once these properties are assigned.
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.
@Pedram since you only know the property names at runtime, yes, you need to enumerate it as a dictionary to get the name/values.
foreach(var kv in (IDictionary<string, object>)recipient) Console.WriteLine("Key:{0} Value:{1}", kv.Key, kv.Value);

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.