Search code examples
c#dynamicsubclassexpandoobject

Can an ExpandoObject have a strongly typed parent?


Using ExpandoObject, is it possible to subclass a class with typed properties and only add dynamically the properties that come up during runtime?

class TypedProperties
{
    public int KnownIntProperty { get; set; }
    public string KnownStringProperty { get; set; }
}

Imagine in my code I dynamically have to add a property SecondStringProperty but still want to take advantage of the TypedProperties. How would I do that?


Solution

  • You can't of course let your ExpandoObject inherit from some other class, because inheritance is fixed and the base class is System.Object.

    Also you can't inherit from ExpandoObject because it's sealed. So if you want to have both: type-safe, non-dynamic regulary declared properties and dynamically added ones, it's getting tricky, and you likely just can map an expando object to an existing object, so the expando is kind of a proxy for the non-dynamic instance.

    You can write code that dynamically adds properties and their values to your ExpandoObject - you find in another classes instance.

    The ExpandoObject is essentially an IDictionary<string, object> of property names and their values.

    var expando = new ExpandoObject();
    expando.SecondStringProperty = "2nd string";
    
    IDictionary<string, object> expandoDic = expando;
    var obj = new TypedProperties { ... };
    foreach (var p in obj.GetType().GetProperties())
    {
       expandoDic.Add(p.Name, p.GetValue(obj));
    }
    //'expando' now contains all public props+values of obj plus the additional prop 'SecondStringProperty'