C#: When working with ExpandoObject, you need to use the dynamic keyword

Posted: (EET/GMT+2)

 

C# is a strictly-typed language, and that's great in my opinion. However, there are situations when you'd need a bit more flexibility, and that's that C#'s dynamic data type can provide. For instance, when working with things like XML, JSON and JavaScript integration, you might need the dynamic data type.

Although this type has been available since C# 4.0, here's a quick demo on how to get started.

The System.Dynamic namespace (in the System.Core assembly in .NET 4.5) contains an useful class named ExpandoObject, which gives you the ability to create properties and methods at runtime. To create an instance of this class, you must use the dynamic keyword like this:

// create an ExpandoObject using the C# dynamic keyword
dynamic d = new ExpandoObject();

After this, you can do neat things like:

// create a property and set its value
d.HelloWorld = "Hello, World!";

// creating a method
d.SayHello = (Action)(() => Console.WriteLine(d.HelloWorld));

// calling a method
d.SayHello();

Note that while you can create an instance of ExpandoObject using the traditional way, this won't work in practice:

// creating an ExpandoObject directly works...
ExpandoObject e = new ExpandoObject();

// ...but, using ExpandoObject directly gives errors; these won't work:
e.HelloWorld = "Hello, again?";
// Error: "System.Dynamic.ExpandoObject" does not contain a definition for "HelloWorld"

e["HelloWorld"] = "Hello, again?";
// Error: Cannot apply indexing with [] to an expression of type "System.Dynamic.ExpandoObject"

Thus, when working with ExpandoObject, remember the dynamic keyword!

And in case you are interested in learning more, check out the DynamicObject type, too!

Happy hacking!