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...");

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.


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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s


A great WordPress.com site

iReadable { }

.NET Tips & Tricks

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: