Some dictionary, "key1" = "Value1, "key2" = "Value2", ...
.
I need to create a object
{
key1 : "Value1",
key2 : "Value2",
...
}
Some dictionary, "key1" = "Value1, "key2" = "Value2", ...
.
I need to create a object
{
key1 : "Value1",
key2 : "Value2",
...
}
You cannot make an object of anonymous type at runtime. Although anonymous types are, well, anonymous, they are static types, i.e. their members are known at compile time. Unless all keys and values of your dictionary are known at compile time (which defeats the purpose, really) you cannot make a static type from the dictionary.
The next closest thing would be to use a dynamic
type with an ExpandoObject
:
dynamic obj = new ExpandoObject();
var tmp = (IDictionary<string,object>)obj;
foreach (var p in dict) {
tmp[p.Key] = p.Value;
}
Now you can write
Console.WriteLine("{0} {1}", obj.key1, obj.key2);
This will compile and run, as long as dict
cntains keys key1
and key2
.