Introduction
The System.CodeDom namespace in .net allows the users to dynamically compile and create assemblies. This concept is used by ASP.NET internally. The article provides an insight on how to create assemblies dynamically.
The following are the list of classes, which would be used to create the assembly:
- CodeNamespace
- CodeTypeDeclaration
- CodeCompileUnit
- CodeEntryPointMethod
- CodeMemberField
- CodeMemberProperty
- CodeMemberMethod
- CodeParameterDeclarationExpression
- CodeCompileUnit
- CompilerParameters
- CodeSnippetExpression
- CodeExpressionStatement
Step 1. Add the following namespace declarations.
The System.The codedom namespace contains the classes/types necessary to create assemblies at runtime. The above-mentioned classes are contained within this namespace.
Step 2. Create the following class.
Any code created from Step 3 to Step 10 must reside in the CcodeGenerator class. For clarity and explanation sake, the article has fragmented the code into pieces.
Step 3. The CodeNamespace class is used to add/create namespaces. The name of the namespace can be passed through the constructor of the class.
Step 4. Using the mynamespace object, add the list of all namespaces that are used by the assembly.
Step 5. Create a class inside the namespace.
Step 6. Create a member and add it to the newly created class.
Step 7. Create a property (with get and set) and add it to the class.
Step 8. Create a method. Please take utmost care when assigning values to the CodeSnippetExpression class, as any statement provided must not have any syntax error(s). Since the assembly would be created at runtime (dynamically), the compiler would simply throw all Compile-time error(s) and we don't have any prudent means to find and eliminate the error.
Step 9. Create a main method (Entry point for the assembly).
Step 10. Compile the class and create the assembly.
Step 11. Create a test component to create the assembly.
The HelloWorld.exe would be created in the mentioned path. The output of the assembly would be as follows.
![Output]()
Conclusion
The facility to dynamically create assemblies would be of immense use when developing real-world applications that demand a great amount of flexibility and scalability.