Click here to Skip to main content
15,894,460 members
Articles / Programming Languages / C#
Tip/Trick

Dynamic Class Construction

Rate me:
Please Sign up or sign in to vote.
4.20/5 (2 votes)
27 Mar 2013CPOL2 min read 13.6K   119   9   2
This article is to give you a brief example of how can anyone construct a class dymamically.

Introduction

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.

Prerequisites

  • 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:
C#
// 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 :
C#
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.

C#
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);
            df.Add(obj);
        }

        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());
        }
        Console.ReadKey();
    }

}

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.

History

  • 25 March 2013 : Initial post.

License

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


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 4 Pin
johannesnestler28-Mar-13 4:36
johannesnestler28-Mar-13 4:36 
GeneralRe: My vote of 4 Pin
Amitpal Rawat31-Mar-13 23:45
Amitpal Rawat31-Mar-13 23: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.