Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend an existing object in c# 4.0 using dynamics

Tags:

c#

dynamic

c#-4.0

I would like to have something similar to javascript's prototype property in c#.
The idea is to extend an instance of a class like you do in javascript.
The closest thing I found was using ExpandoObject, but you can't initialize it with an existing object.
Another problem is that you can get back the original object from the ExpandoObject.

Here is what I want to do:

var originalObject = new Person();
originalObject.name = "Will";
var extendedObject = new ExpandoObject();
extendedObject.lastName = "Smith";

//do something

originalObject = (Person) extendedObject;
like image 593
Pato Loco Avatar asked Nov 30 '12 18:11

Pato Loco


1 Answers

You can partially solve the problem using something like:

public static class DynamicExtensions
{
    public static dynamic ToDynamic(this object value)
    {
        IDictionary<string, object> expando = new ExpandoObject();

        foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType()))
            expando.Add(property.Name, property.GetValue(value));

        return expando as ExpandoObject;
    }
}

But you are not able to copy the methods to the new ExpandoObject

like image 53
Pato Loco Avatar answered Nov 04 '22 03:11

Pato Loco