In C#, we can create classes at run-time and compile it to generate an assembly using System.CodeDom namespace in System.dll. For this, It provides different classes and functions to create the dynamic namespace add classes, methods and properties to it.
Let's start by adding a new Console application and add the namespace using System.CodeDom to it. We will create a namespace say 'sampleNamespace' by using the CodeNamespace class. So our code will look like the following:
Next, we will add the using's to be used in the dynamic code. This is similar to adding the namespaces which we add normally in our applications as: using System or using System.Linq. To do this, we will use the Imports function in the CodeNamespace class. So our code will look like the following:
Next we will add a class named SampleClass to our namespace sampleNamespace using the CodeTypeDeclaration class. It provides different properties like Name, IsClass, Attributes etc. to create class definition and add this class to our namespace sampleNamespace. So the code will look like the following:
Next we will use the CodeCompileUnit class, which will acts as a container for the dynamic code that we are trying to generate. This container will be used to compile and generate an assembly of our code. Let's create a physical file on our system using the CodeCompileUnit class using the StreamWriiter class. So our code will change to the following:
So our complete code will look like below:
So this was about how we can generate dynamic class with namespace using CodeDom classes. In next article we will see how we can add methods to these classes. Hope you enjoyed reading it. Happy coding...!!!