-1

Some dictionary, "key1" = "Value1, "key2" = "Value2", .... I need to create a object

{ key1 : "Value1", key2 : "Value2", ... }

Mohit Jain
  • 135
  • 1
  • 4
  • 12
  • SmartFormat.Net library requires you to pass object in the form mentioned above @grant – Mohit Jain Oct 09 '15 at 01:24
  • Possible duplicate of [Convert string to object in c#](http://stackoverflow.com/questions/33027613/convert-string-to-object-in-c-sharp) – Mick Oct 09 '15 at 06:24
  • You might not need to do this. SmartFormat.NET handles dictionaries. `var dict = new Dictionary() { {"Name", "Smart"},{ "Address", new { City = "GitHub", State = "WWW" } } }; Debug.Assert("Smart from GitHub, WWW" == Smart.Format("{Name} from {Address.City}, {Address.State}", dict));` – Tom Blodget Oct 09 '15 at 06:24
  • Rather than adding more questions you should be modifying the original question http://stackoverflow.com/questions/33027613/convert-string-to-object-in-c-sharp.... – Mick Oct 09 '15 at 06:26

1 Answers1

4

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    Does not work: if obj is declared as ExpandoObject the compiler gives error message: Cannot apply indexing with [] to an expression of type 'System.Dynamic.ExpandoObject'. The same message appears at runtime if obj is declared as dynamic. – Almis Sep 28 '17 at 09:12
  • @Almis I forgot that you need to cast `ExpandoObject` to dictionary. See the edit. – Sergey Kalinichenko Sep 28 '17 at 10:05