tags:

views:

162

answers:

3

Hi there,

Let's say in the constructor of my .NET class I want to write code that will actually add methods to my class dynamically. So now when I reflect over my class I will see the methods where as when I first built the project the methods didn't exist

How can I achieve this?

I've been looking up CodeDom but it's all a bit confusing

A: 

I.... can't imagine why you would want to do this.

Could you explain why you would want to?

Instead, try having different concrete implementations of the same interface, or abstract class if you're sharing most of the code.

Luke Schafer
I'm trying to accomplish this:http://stackoverflow.com/questions/885682/creating-udf-with-vsto-in-excelRead the last sentence of the post
+1  A: 

you have to either use Reflection.Emit or Mono.Cecil or PostSharp.

All of them are easy to learn...

Ali Shafai
+2  A: 

Once you've loaded the assembly, you cannot change it. You can use Reflection.Emit or CodeDom to dynamically compile a new assembly, with a class that is just like yours + extra methods, but it will not change the existing (at least existing at runtime) class. Potentially, you could load your class in a separate AppDomain, create a new class that was a "copy" of it with the extras, then load that assembly in your main AppDomain (and unload the one where you loaded your original class). You're still creating a new class, not adding to an existing one, but the effect would be similar.

You can use code injection to insert code before the class is loaded, however. There are some code injection frameworks for .NET that would help with this... but that is different than your specific question.

Reed Copsey