Is it possible to add a method to the EXISTING class at run time? Why or why not?

I would suggest that this could use Reflection.Emit,

but a similar question in SO only answers how to dynamically create a class / method, and not how to update an existing class.

In a similar vein, is it possible to remove methods / classes at runtime? If so, I suggest that you can simply delete the class and add it back with the old methods plus the new one.

Thanks in advance.

PS For this, I have no intentional use, this is just a matter of curiosity.

+8
c # dynamic
source share
2 answers

In regular C # /. NET, the answer is simply no. The most you can do is write DynamicMethod , which can behave like a method of this type (access to private fields, etc.), but it will never be in the API - you just end up with a delegate.

If you use dynamic , you can do almost anything you want. You can emulate this with ExpandoObject by adding delegates instead of methods, but you can do anything with a custom dynamic type, but that only affects those who use the dynamic API. For a basic ExpandoObject example:

 dynamic obj = new ExpandoObject(); Func<int, int> func = x => 2*x; obj.Foo = func; int i = obj.Foo(123); // now you see it obj.Foo = null; // now you don't 

For properties and events (rather than methods), you can use the System.ComponentModel approach to change what appears at run time, but this only affects callers who access through System.ComponentModel , which basically means: bind user data interface. This is how a DataTable presents columns as pseudo-properties (forgetting about the “typed data sets” at the moment - it works without them).

For completeness, I should also mention extension methods. This is more of a compiler trick rather than a run-time trick, but curious allows you to add methods to an existing type - for small values, add.

One final trick commonly used by ORM, etc., is to dynamically subclass a type and provide additional functions in a subclass. For example, redefining properties to intercept them (lazy loading, etc.).

+26
source share

Is it possible to remove methods / classes at runtime?

Suppose it is possible. Calls to these methods will fail and produce undefined behavior (but usually catastrophic).

Therefore, I am sure that this is impossible.

+3
source share

All Articles