The Expando Object

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