A basic example of using the ExpandoObject for dynamic types in .NET C#

The ExpandoObject in the System.Dynamic namespace is an interesting option if you ever need to write dynamic objects in C#. Dynamic objects are ones that are not statically typed and whose properties and methods can be defined during runtime. I’ve come across this object while I was discovering the dynamic language runtime (DLR) features in .NET. We’ve seen an example of that in this post with the “dynamic” keyword.

You can add properties and methods to an ExpandoObject on the fly. Let’s build a simple calculator in a dynamic manner:

dynamic calculator = new ExpandoObject();
calculator.Type = "Dynamic expandable calculator";
calculator.Add = new Func<int, int, int>((firstDigit, secondDigit) => { return firstDigit + secondDigit; });
calculator.Subtract = new Func<int, int, int>((firstDigit, secondDigit) => { return firstDigit - secondDigit; });
calculator.Multiply = new Func<int, int, int>((firstDigit, secondDigit) => { return firstDigit * secondDigit; });
calculator.Divide = new Func<int, int, double>((firstDigit, secondDigit) => { return firstDigit / secondDigit; });
calculator.Describe = new Action(() => Console.WriteLine("This is a dynamic calculator."));

These elements will be saved in an underlying Dictionary where the names of the properties and functions are the keys and their definitions are the values. Here’s an example of how you can invoke the members of the calculator. Note that as you type the below code you won’t get any IntelliSense help when testing for “calculator.”. This is expected, as we’re dealing with dynamic code. You’ll have to type the members correctly otherwise you’ll get an exception at runtime:

int d1 = 10;
int d2 = 2;

Console.WriteLine("Calculator type: {0}", calculator.Type);
Console.WriteLine("Addition: {0}", calculator.Add(d1, d2));
Console.WriteLine("Subtraction: {0}", calculator.Subtract(d1, d2));
Console.WriteLine("Multiplication: {0}", calculator.Multiply(d1, 2));
Console.WriteLine("Division: {0}", calculator.Divide(d1, d2));
Console.WriteLine("Description action invoked...");
calculator.Describe();

Here’s the output from the console window:

Calculator type: Dynamic expandable calculator
Addition: 12
Subtraction: 8
Multiplication: 20
Division: 5
Description action invoked…
This is a dynamic calculator.

You can also extract the member names from the underlying dictionary. Again, there will be no IntelliSense when typing “member.”, but “Key” and “Value” are well-known members of the Dictionary object anyway:

foreach (var member in calculator)
{
	Console.WriteLine("{0}: {1}", member.Key, member.Value);
}

Here’s the output:

Type: Dynamic expandable calculator
Add: System.Func`3[System.Int32,System.Int32,System.Int32]
Subtract: System.Func`3[System.Int32,System.Int32,System.Int32]
Multiply: System.Func`3[System.Int32,System.Int32,System.Int32]
Divide: System.Func`3[System.Int32,System.Int32,System.Double]
Describe: System.Action

My first reaction to all this was “interesting, but what’s the point?” Apparently I’m not the only person wondering about this. Here‘s a thread on StackOverflow you can read through. The thread refers to an MSDN post with a more realistic application of ExpandoObject available here.

If any reader has used ExpandoObject in a real life scenario then they are welcome to present a description in the comments section below.

View all posts on Reflection here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

3 Responses to A basic example of using the ExpandoObject for dynamic types in .NET C#

  1. Ignas says:

    Could ExpandoObject be used for de-serialization? For example to replace something like JsonConvert.DeserializeObject(httpResponse).

  2. Ignas says:

    I mean instead of having YourType defined maybe could have something more dynamic and universal. Sorry for the previous brief comment 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: