2

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".

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Henrik Berg
  • 519
  • 5
  • 21
  • 2
    Although this does not directly answer the question as per your title, you can create a contructor for `Person` that takes a dynamic object as a parameter and read the properties you want. `public Person(dynamic myDynamicObject) { this.Name = myDynamicObject.Name; }` – Flater Jun 06 '17 at 08:29
  • The question code has nothing to do with *inheritance*. You are trying to *explicitly cast* a dynamic object to a specific type. This is allowed either when there's an inheritance relation or when there is an explicit cast operator. – Panagiotis Kanavos Jun 06 '17 at 09:25

1 Answers1

1

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.

user9993
  • 5,833
  • 11
  • 56
  • 117