Click here to Skip to main content
12,824,787 members (41,730 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


9 bookmarked
Posted 26 Mar 2013

Dynamic Class Construction

, 27 Mar 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
This article is to give you a brief example of how can anyone construct a class dymamically.


This Console Application is a pure example of how can we construct a class or any code dynamically using reflection. This can be used when you know a structure or piece of code at run time.


  • You should have prior knowledge of C# or any other Object Oriented Language.
  • Little bit of knowledge of reflection. How does it works.

Using the code

In this application i have created two compile time classes and one dynamic (run time) class .

  • Compile Time Classes: One of the class is used to create a dynamic class using a string value. And the other class uses the instance of that dynamic class to assign values.
  • Dynamic Class: This class we pass it as a string value and will be compiled at run time.

As I'm not good at explaining things, I'll try my level best to explain code to you. So, here is the code.

First class is "Compile_Code" which is use to compile a dynamic class. It consists of two functions CompileClass and CompileScript.  

  • CompileClass: In this function we create a string of whatever code we want to execute at run time. I have created a class with two variable and their get and set properties. This function returns an Assembly of the code executed. Here's a code of mine:
// This method returns the Assembly. Which is used to access properties of that class !!!
public Assembly CompileClass()
    string code = @"
         public class Test
            public string name{get; set;} 
            public int age{get; set;}


    CompilerResults compilerResults = CompileScript(code);

    if (compilerResults.Errors.HasErrors)
        throw new InvalidOperationException("Expression has a syntax error.");

    Assembly assembly = compilerResults.CompiledAssembly;

    return assembly;

In the above code, string value "code" consists of a code which we want to execute at run time. And passes that string to "CompileScript" function. If any syntactical error is found, it catches the error and throws an exception.

  • CompileScript: This function is used to set the compiler parameters , providing the environment and returning the compiled assembly. Here's the code :
public  CompilerResults CompileScript(string source)
    CompilerParameters parms = new CompilerParameters();

    parms.GenerateExecutable = false;
    parms.GenerateInMemory = true;
    parms.IncludeDebugInformation = false;

    CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp");

    return compiler.CompileAssemblyFromSource(parms, source);

In the above code, we are setting parameters like:

  • GenerateExecutable: This is a bool value which sets compiler property to generate a executable file or not. 
  • GenerateInMemory: As name suggest to generate space in memory.

These are the two basic functions which helps me to executing a piece of code dynamically. Use them or i say play with them and have fun coding.

Now here is the class which i have created to play with the assembly which has been created dynamically. Have a look at it, and mold it in Your own way.

class Program
    static void Main()
        Compile_Code tv = new Compile_Code();
        Assembly assembly = tv.CompileClass();
        List<object> df = new List<object>();

        // This dictionary is to bind data.You can use any kind of data to bind. 
        Dictionary<string,int> tst1 = new Dictionary<string,int>();
        tst1.Add("Amit", 23);
        tst1.Add("Vijay", 24);
        tst1.Add("Sumit", 25);
        tst1.Add("Rawat", 26);
        tst1.Add("Coool", 27);

        foreach (KeyValuePair<string, int> d in tst1)
            object obj = assembly.CreateInstance("Test");
            obj.GetType().GetProperty("name").SetValue(obj, d.Key, null);
            obj.GetType().GetProperty("age").SetValue(obj, d.Value, null);

        foreach (object obj in df)
           Console.WriteLine(obj.GetType().GetProperty("name").GetValue(obj, null).ToString());
           Console.WriteLine(obj.GetType().GetProperty("age").GetValue(obj, null).ToString());


As we don't know at compile time that what would be the return type of the class is, so I have created a list of object type and assigning the value to the list using the dynamic class.

Here I'm using reflection to get and set the properties of the dynamic class.

That is a pretty simple example, I hope that you got the idea behind it.

Thank you very much for reading.


  • 25 March 2013 : Initial post.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Amitpal Rawat
Software Developer
India India
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralMy vote of 4 Pin
johannesnestler28-Mar-13 5:36
memberjohannesnestler28-Mar-13 5:36 
GeneralRe: My vote of 4 Pin
Amitpal Rawat1-Apr-13 0:45
memberAmitpal Rawat1-Apr-13 0:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170308.1 | Last Updated 28 Mar 2013
Article Copyright 2013 by Amitpal Rawat
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid