Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a reserved word (Type name) as ExpandoObject or Dynamic property

Tags:

How can I possibly set a property of an ExpandoObject with a key that is a reserved word?

Like this:

dynamic query = new ExpandoObject();
query.size = 10;
query.date = "2017-04-27";

dynamic match = new {
  query = query,
  bool = true
}
like image 465
Sulaiman Adeeyo Avatar asked Apr 27 '17 09:04

Sulaiman Adeeyo


1 Answers

In ExpandoObject you may use any string value as a property name (including reserved words, spaces, etc., even empty string) via casting the ExpandoObject instance to IDictionary<string, object>:

dynamic query = new ExpandoObject();
(query as IDictionary<string, object>)["bool"] = true;
(query as IDictionary<string, object>)[" b o o (g)? l \"e:)\""] = false;
(query as IDictionary<string, object>)[""] = true;

but you won't be able to access such properties using "plain C# syntax" (i.e. obj.prop). You'd have to cast the object to IDictionary<string, object> and access them using indexer:

var qDict = query as IDictionary<string, object>;
Console.WriteLine(qDict["bool"]);
Console.WriteLine(qDict[" b o o (g)? l \"e:)\""]);
Console.WriteLine(qDict[""]);
// Prints:
//   True
//   False
//   True
like image 131
Dmitry Egorov Avatar answered Sep 22 '22 10:09

Dmitry Egorov