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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With