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.
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#)
CodeNameSpace is the core object which wraps the entire code generation logic.
Create a namespace, include some imports and adding comments.
Declare a class and add a property to the class.
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.
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
Then you can pass any TextWriter object, here I’ve used StreamWriter and generating a physical file. Compact code in my fashion.
Sample contains code for
- generating constructors
- creating .NET 4.0 type parameters
- private properties
- adding attributes
- adding methods
- adding code inside the methods.