Hey guys, I was wondering if there is a way for me to change the properties a class has (add/remove properties) on runtime..
Is this possible?
Hey guys, I was wondering if there is a way for me to change the properties a class has (add/remove properties) on runtime..
Is this possible?
You cannot do this unless you are working with an instance of ExpandoObject. The metadata for a CLR type is fixed in the assembly and cannot be changed at execution time. If you really need this kind of dynamic behavior you must use a dynamic type (like EpandoObject) that supports this behavior.
Just to add to Andrew Hare's reply: With C# 4 and .NET 4 you can inherit from DynamicObject and redefine what it means to take various actions on an instance of the type. DynamicObject defines a number of virtual methods that you can override to take control of what it means to e.g. access a property. You could use this to allow properties to be added/removed to the instance, which is pretty much what ExpandoObject does.
For more about ExpandoObject see this question and this blog post.
For UI development (i.e. what is presented to the end user) look at implementing ICustomTypeDescriptor (in System.ComponentModel). Many controls are aware of this interface and will use it to query the properties an instance or type exposes.
If you are on 3.5 you can use IL to create a dynamic type, and also accomplish the task, but it's a lot harder, but there are some frameworks for doing that I suppose.