5

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
  • 3
    VS already does almost all of this. Type class Foo: IFoo. Put the cursor on IFoo and press Ctrl+.. VS will generate the code. Commented Aug 23, 2010 at 14:17
  • @CraigStuntz the VS auto-generation is pretty good, but it would be nicer if it could be told to generate stubs that forward invocations to some other object. Commented Nov 13, 2017 at 22:57

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The question is about generating class's source code. At least that is how i read it.
I would definitely not try to emit IL and then reverse compile it that is very strange considering how easy it is to write plain text c sharp stubs in less than 100 lines of code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.