Henrik Berg
Henrik Berg

Reputation: 549

Can I cast a DynamicObject or ExpandoObject to a specific type?

Let's say I have the following class:

class Person
{
  public String Name { get; set; }
  public String Address { get; set; }
}

And then I create a dynamic object, like this:

dynamic person = new ExpandoObject();
person.Name = "Henrik";
person.Address = "Home";
person.Age = 100;

Now, is it possible in any (preferrably simple) way to convert the created object into an object of (a subclass of) the class Person? Doing this doesn't work:

var p = (Person)person;

since the person object is not related to the class Person in any way, it just happens to contain all the properties of the class Person. But is it possible to make the conversion work anyway, in a simple and generic way? Ideally, I would like to be able to cast my person object into a subclass of Person, which contains (obviously) all the properties of Person, in addition to (in this example) the new property "Age".

Upvotes: 2

Views: 4733

Answers (1)

user9993
user9993

Reputation: 6180

No, you can't retroactively apply inheritance or an interface like that. That just isn't how C# or most languages work. See this answer for a discussion on the differences between dynamic, ExpandoObject, and DynamicObject.

You could implement the IDynamicMetaObjectProvider interface, or even inherit from DynamicObject as shown here.

This would allow you to add dynamic-ness to your new type.

Upvotes: 1

Related Questions