Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change class definition on runtime?

Tags:

c#

.net

Is there a way for me to change the properties a class has (add/remove properties) on runtime?

like image 441
mcabral Avatar asked Dec 03 '22 05:12

mcabral


2 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.

like image 166
Andrew Hare Avatar answered Dec 04 '22 18:12

Andrew Hare


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.

like image 27
Brian Rasmussen Avatar answered Dec 04 '22 17:12

Brian Rasmussen