Is there a way for me to change the properties a class has (add/remove properties) on runtime?
-
4The real question is why do you want to do this? You're probably fixing the wrong problem. – djdd87 May 04 '10 at 13:04
-
@GenericTypeTea academic question :) (Not homework, just me with some friends discussing the possible of this) – mcabral May 04 '10 at 13:40
-
Ah, fairy'noof then! Academic'erise away. – djdd87 May 04 '10 at 14:30
-
http://download.oracle.com/javase/1.4.2/docs/guide/jpda/enhancements.html : "Tool (IDE) vendors want the ability to do fix-and-continue debugging. That is, while debugging, identify a problem, fix it, and continue debugging with fixed code. Organizations deploying long running servers wish to be able to fix bugs without taking down the server." – jamie Sep 13 '11 at 23:24
5 Answers
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.

- 344,730
- 71
- 640
- 635
-
6I've never heard of `ExpandoObject` before now, and I'm so glad my co-workers have never heard of it either. – MusiGenesis May 04 '10 at 13:12
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.

- 1
- 1

- 114,645
- 34
- 221
- 317
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.

- 2,498
- 16
- 23
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.

- 500
- 2
- 9
-
Dynamic code injection, actually I'm doing a framework just for that. You can define some C# attributes and then inject the code, where you want it. It's good for separation of concerns. – BartoszAdamczewski May 04 '10 at 13:45