Generating code using System.CodeDom

Posted on Updated on

Get the code sample for this post git

We face several occasions that we need to generate code by automation. Several tools do exist in order to automate the code generation. In this article I discuss about the System.CodeDom which is part of .NET SDK.

CodeDom is designed in the provider model and it gives the flexibility to initiate with the desired .NET language, so we can create the code generation algorithm and ask CodeDom to generate the code in different languages like C#, VB or C++.

Place these using statements before begin.

image

 

 

You can get the list of languages supported by the CodeDom provider from this code. Output will contain different names for same language (like csharp and c#)

image

 

 

 

 

CodeNameSpace is the core object which wraps the entire code generation logic.

 

Create a namespace, include some imports and adding comments.

image 

 

 

 

 

 

 

 

Declare a class and add a property to the class.

image

 

 

 

 

 

 

 

 

 

Like above CodeDom also provides methods to create private variables, constructors, methods, attributes and even logic inside methods. The downloadable sample has demonstration for all the features.

After adding all the required elements for the code we can add the types to the namespace.

image

 

 

Once the namespace is created we have to generate the code, here the CodeDom magic works. In order to generate  the code we should use the following method

CodeDomProvider.CreateProvider(“language“).GenerateCodeFromNamespace(codeNamespace, textWrtier, codeGeneratorOptions)

Creating the CodeGeneratorOptions

image

 

 

 

Then you can pass any TextWriter object, here I’ve used StreamWriter and generating a physical file. Compact code in my fashion.

image

 

 

 

Sample contains code for

  • generating constructors
  • creating .NET 4.0 type parameters
  • private properties
  • methods
  • adding attributes
  • adding methods
  • adding code inside the methods.

Get it from github

Advertisements