Google Search: c# expando

One of the queries that came to my site the other day was: c# expando. Now you could take this to mean one of several things:

  1. Creating JavaScript Expando Objects in C#
  2. Creating C# Expando classes for use in C#
  3. Something Else

If it is something else, email me: and I will see if I can shed any light.

If however it is choice 1, I know how to do this, but it can be quite a big subject. In IE it is really simple to do, you can simply use an attribute on a class and there you have an expando. Basically an expando is an arbitary object that is attached created at runtime on another. If you want you can also use setAttribute on the object and add a variable that way.

function Kinlan(){this.Test = 1;}

var currKin = new Kinlan();

currKin .Test = 2;currKin .Bleep = "bleeeep";

The Object currKin, will have two properties, one test, the other Bleep. It is that simple.

To do it in C# when creating javascript wouldn't be too different. You would just have to make sure your JavaScript looked like that above. You could also attach new attributes to HTML Elements from C# which would be "expandoesk". Say you had a table t and you wanted to have a flag on it called readyToDelete you could add it to the Page via something similar to:

HTMLTable t = new HTMLTable();t.ID="testTable";t.Attributes.Add("readyToDelete", "false");...

The above code would create a HTMLTable with an attribute called readyToDelete with the value false.

Going back to the begining; if it was option 2, I am not too sure how you would achieve dynamic addition of properties or variables to an object, but I assume it would involve Reflection and a lot of extra leg work. I know that there is also such a thing as an ExtenderProvider, but again I am not too sure how it works [Tooltips in Winforms extend the Class that it is attached too by providing an new Propery called "ToolTip"].

I have also heard that C# 3.0 may provide this type of functionality but that is just hearsay, I haven't actually read the spec.

I will look up the Reflection methods; the ExtenderProvider and also C# 3.0 spec.

I lead the Chrome Developer Relations team at Google.

We want people to have the best experience possible on the web without having to install a native app or produce content in a walled garden.

Our team tries to make it easier for developers to build on the web by supporting every Chrome release, creating great content to support developers on, contributing to MDN, helping to improve browser compatibility, and some of the best developer tools like Lighthouse, Workbox, Squoosh to name just a few.

I love to learn about what you are building, and how I can help with Chrome or Web development in general, so if you want to chat with me directly, please feel free to book a consultation.

I'm trialing a newsletter, you can subscribe below (thank you!)