|February 24, 2015

Daily Archives: February 24, 2015

.NET Coding

Dynamic objects in C#

Published by:

I know that it is not what strongly typed language is supposed to support but sometimes we need to add properties on the fly as in JavaScript. Here are two alternative ways to do that:

One way is to use the ExpandoObject that is being shipped in System.Dynamic. We can add properties (of any type) on the fly and to consume them afterwards. Consider the following example:

        dynamic dynamicObject = new ExpandoObject();
        dynamicObject.myCat = cat;
        dynamicObject.myCar = car;
        dynamicObject.justAString = "I am just a string";
        dynamicObject.justAnInteger = 42;

If we try to consume a property that is not present we get an exception. No need to say that you have to say good bye to intellisense.

The second way is to implement a class with an indexer and an underlying dictionary as the data store. You can add properties on the fly with a slightly different syntaxis. Consider the following example:

public class ViewBag
    public ViewBag()
        dict = new Dictionary();

    private Dictionary dict;

    public object this[string index]
            object val=null;
            dict.TryGetValue(index,out val);
            return val;
            if (dict.ContainsKey(index))
                throw new Exception();

and that is how we add properties

        var viewBag = new ViewBag();
        viewBag["mycar"] = car;
        viewBag["myCat"] = cat;
        viewBag["justAString"] = "I am just a string";
        viewBag["justAnInteger"] = 42;

I have named it viewBag purposefully because the actual MVC ViewBag is built this way.

I must admit that it is mainly border scenarios where you might need those but you never know.