In this article, we will see how we can create C# class at run-time and compile it to generate an assembly. System.CodeDom namespace in System.dll provides different classes and functions, using which we can create the dynamic namespace, add classes to it, and then add methods and properties to it.
To start with, we will add a new Console Application and add the namespace, using System.CodeDOM to it. First, we will create a namespace of our choice, say 'myNamespace'. For this, we will use the CodeNamespace class. Thus, our code will look like:
- CodeNamespace nameSpace = new CodeNamespace("myNameSpace");
Next, we will add our list to be used in the dynamic code and we are going to generate it. This is nothing but dynamically adding the namespaces which we add normally in our Applications such as: using System or using System.Linq. For this, we will use the Imports function in the CodeNamespace class. Thus, our code will look like:
- nameSpace.Imports.Add(new CodeNamespaceImport("System"));
- nameSpace.Imports.Add(new CodeNamespaceImport("System.Linq"));
- nameSpace.Imports.Add(new CodeNamespaceImport("System.Text"));
Next, we will add a class named MyClass to our namespace myNamespace, using the CodeTypeDeclaration class. This class will provide different properties like Name, IsClass, Attributes etc., which are used to configure our class definition. Thus, this class will be added to our namespace myNamespace. Hence, the code will look like:
- CodeTypeDeclaration cls = new CodeTypeDeclaration();
- cls.Name = "MyClass";
- cls.IsClass = true;
- cls.Attributes = MemberAttributes.Public;
- nameSpace.Types.Add(cls);
Next, we will use the CodeCompileUnit class. This acts as a container, which will be used as a container for the entire code we have written to compile and generate an assembly for it. To see, how the code looks, let's create a physical fill on our system, using the CodeCompileUnit class. For this, we will use StreamWriter class. Thus, our code will change to the following:
- CodeCompileUnit compileUnit = new CodeCompileUnit();
- compileUnit.Namespaces.Add(nameSpace);
- CSharpCodeProvider csharpcodeprovider = new CSharpCodeProvider();
- CSharpCodeProvider provider = new CSharpCodeProvider();
- using (StreamWriter sw = new StreamWriter(@"D:\TestFile.cs", false))
- {
- IndentedTextWriter tw = new IndentedTextWriter(sw, " ");
- provider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions());
- tw.Close();
- }

Madhu KumarPosted Oct 18, 2016, 4:02 PM
Can it be excuted rather saving to external file? i mean how to use this class in any other class?
Bhavik PatelPosted Aug 22, 2016, 10:47 PM
Nice
Ramesh PalaniappanPosted Aug 22, 2016, 1:48 AM
Good One
SubashPosted Aug 22, 2016, 12:56 AM
Thanks for nice article