C# dynamic: Assign properties dynamically

1.3k views Asked by At

I am writing a wrapper around some data library that executes sql statements and returns results.

The ExecuteQuery command should ideally return an IEnumerable<T> depending on what type of object the query results map to. The problem is that I cannot know what type this would be and therefore I would rather return a IEnumerable<dynamic> type.

This is all good so far except that I want the dynamic objects properties to be the same as the columns being queried for but I cannot find anyway to assign this, I currently have all the column names in an array col[] e.g.

dynamic obj = new {} as dynamic;
for(int i = 0; i < col.Length; i++){
    //say col[i] == 'id', I want obj.id = someValue 
    obj.? = someValue;  ???
}

I hope this is clear. I hope it's not impossible!

p.s. I am writing this for WP7 so my options are severely limited, it might be good to keep this in mind.

Thanks for you help.

1

There are 1 answers

6
Daniel Hilgarth On

dynamic is not applicable in your case. You use dynamic when you know the property name at compile time but not the actual type that property will be defined on.

If you know the property name only at runtime you will have to use ordinary reflection, something like this:

obj.GetType()
   .GetProperty(col[i])
   .SetValue(obj, someValue);

Please note that dynamic obj = new {} as dynamic; makes absolutely no sense. This will create an anonymous type without any properties. Assigning it to a dynamic variable doesn't change the fact that it doesn't have - and never will - any properties.

If you are trying to dynamically add properties to an object, you might want to use ExpandoObject.

Usage would be like this:

IDictionary<string, object> obj = new ExpandoObject();
for(int i = 0; i < col.Length; i++)
{
    obj.Add(col[i], someValue);
}

return (dynamic)obj;