How to add a property at runtime to an already created class C#

Question:

I need to add properties in GridDataSourceBase class at runtime, can anyone help me how to do this?

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

Answer:

One hypothesis is to use ExpandoObject .

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

Most likely you will have to copy the old object's properties 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

Scroll to Top
AllEscort