The Expando Object

Mushrooms
Just some mushrooms

The Expando object has been around for a while. In fact it was in .NET 4.0, in the ancient days of 2009.

I am sure, that back then, I must have thought that it was neat. Maybe a bit like JavaScript, but I never had a use for it until recently.

What is the Expando Object

Technically it is the ExandoObject. It is a class in the System.Dynamic namespace. It gives you a very powerful tool by allowing you to create and remove members and values at run time.

That is just a very brief simplistic explanation of it, but it is straight to the point. You create an object that you can add objects and values to at run time. Sounds a lot like JavaScript but this is in C#. I would not recommend you code everything as an ExpandoObject though. It is a powerful tool, and with great power comes great responsibility.

A Use Case

I actually ran across a use case for this very object. The request was to create a Rest API that could respond quickly. For this project it had some APIs already, but they returned a vast amount of data. This new request only wanted a tiny subset of data. In fact they wanted to specify what fields would be returned in the JSON object.

At first I thought about just using a Dictionary object. I had some concerns about its performance and the complexity of our data models. Doing some searching I found or rediscovered the ExandoObject.

Creating an ExpandoObject and populating it as needed turned out to be the perfect trick. I then return this object as JSON which worked perfectly.

About SheldonS

Web developer for over 15 years mainly with Microsoft technologies from classic ASP to .NET 4. Husband, father, and aspiring amateur photographer.

Posted on February 25, 2019, in .NET, Bits, C# and tagged , . Bookmark the permalink. Leave a 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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: