To add runtime property to an already created class C#

Asked

Viewed 484 times

3

I need to add properties in the Griddatasourcebase class at runtime, someone can help me how to do this?

public class GridDataSourceBase : IGridDataSource
{
    public long Handle { get; set; }
}

1 answer

1

One hypothesis is to use the ExpandoObject.

dynamic objeto = new ExpandoObject();
objeto.Propriedade = 1;

You will most likely have to copy the properties of the old object to this object. You can do it as follows:

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

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

        return expando as ExpandoObject;
    }
}

var tuple = Tuple.Create(1, 1);
var newTuple = tuple.ToDynamic();
newTuple.Item3 = 1;

Source

Browser other questions tagged

You are not signed in. Login or sign up in order to post.