How Can I add properties to a class on runtime in C#?

You cannot extend an existing class with new members at runtime. However, you can create a new class using System.Reflection.Emit that has the existing class as base class.

typeBuilder.SetParent(typeof(MyClass));
typeBuilder.DefineProperty("Prop1", ..., typeof(System.Int32), null);
...

See TypeBuilder.DefineProperty Method (String, PropertyAttributes, Type, Type[]) for a full example.

Leave a Comment