views:

63

answers:

1

Hi,

I'm trying to write a code that allows a user to load an assembly (DLL file), choose an interface in said assembly, than generates a class inheriting that interface, with stubs for all required methods.

The class would be generated either into a file or into an active VS session (the code is intended for use inside an IWizard initialized during project creation through a custom template).

I got to the point where I have the Type object of the interface, but I'm having a hard time figuring the next part, I've contemplated running across the interface's methods in a loop and copying them into a textual file, adding the stub implementations in the appropriate places but I'm pretty sure there's some better method, perhaps through a third party tool?

Any help would be appreciated, Thank you in advance.

+2  A: 

If you want to create a new type at runtime, you'll need to use Reflection.Emit. Reflection.Emit allows you to emit Intermediate Language directly into the current AppDomain (or an assembly if you prefer.) You probably want to use the type in memory, so you may not want to create an actual assembly.

Creating new type is done with the TypeBuilder class.

Codeproject has an excellent introduction: http://www.codeproject.com/KB/dotnet/Creating_Dynamic_Types.aspx

UPDATE:

It has been brought to my attention that the goal is to add a C# code file to an existing project. You would still need to reflect into the assembly and emit IL, but then you'd have to "dissasemble" the IL into C#. Reflector is the #1 recommended tool for this, though I'm not sure it can be automated in the way you want.

Dave Swersky
The question is about generating class's source code. At least that is how i read it.
Constantin