I\'ve noticed that the new ExpandoObject
implements IDictionary
which has the requisite IEnumerable
Using the idea from @samedave, and adding reflection, I got this:
void Main()
{
dynamic foo = new ExpandoObject().Init(new
{
A = true,
B = "Bar"
});
Console.WriteLine(foo.A);
Console.WriteLine(foo.B);
}
public static class ExtensionMethods
{
public static ExpandoObject Init(this ExpandoObject expando, dynamic obj)
{
var expandoDic = (IDictionary)expando;
foreach (System.Reflection.PropertyInfo fi in obj.GetType().GetProperties())
{
expandoDic[fi.Name] = fi.GetValue(obj, null);
}
return expando;
}
}
But it would be nicer to be able to just do it like:
dynamic foo = new ExpandoObject
{
A = true,
B = "Bar"
};
Please vote for this feature in Visual Studio UserVoice.
Update:
Using Rick Strahl's Expando implementation you should be able to do something like this:
dynamic baz = new Expando(new
{
A = false,
B = "Bar2"
});
Console.WriteLine(baz.A);
Console.WriteLine(baz.B);