bandreas
bandreas

Reputation: 907

C# code generation (visual studio template or resharper addin)

I would like to generate some C# code based on existing code. More precisely I need some mappers for existing enums as well as converters, unit-tests for them. It would be a longer discussion why I've generate this code rather than go for a generic approach, but considering that I would like to generate some classes based on some enumeration types, what options would I have? I am just thinking about visual studio extensions, some templates or maybe resharper addins but so far I haven't done anything like this... I would appreciate any input of those of you who had previous experience with such a task.

Upvotes: 1

Views: 1959

Answers (2)

Tedy Pranolo
Tedy Pranolo

Reputation: 1425

Reegenerator supports generating code from existing code. You can create a code generator and then attach it to the file that contains the enum type. The generator will be executed everytime the file is saved. The code generator are given access to the Visual Studio DTE Object, which will give you the code structure through CodeElement classes (CodeClass, CodeAttribute, etc). From there you can either generate a separate partial file through a T4-like template, or simply manipulate the code directly using the DTE EditPoint.

Upvotes: 0

citizenmatt
citizenmatt

Reputation: 18573

ReSharper supports Live Templates as a means of generating code. You can create whatever code you like in there, with editable or linked hotspots to provide customisation points (e.g. current file name, class name, time, new guids, suggested variable names, etc). You can generate code snippets in existing files, surround existing code, or create new files. ReSharper 8 also introduces support for multi-file templates, creating more than one file at a time.

However, ReSharper's templates don't support things like loops - you can't loop over an XML file and generate a class member for each element, for example. T4 would be a better solution for that.

Upvotes: 2

Related Questions