Search code examples
c#.netdynamic-class-creation

Creating dynamic class from a string containing the class definition


I have a stored procedure which accepts the table name, then it reads the table structure and returns me the table structure in the form of a class definition in a string.

E.g.:

string myString = 
 "
   public class TableName
   { 
     public int Column1 { get; set; } 
   }
 "

Is it possible a create a Class/Type from the string containing the class definition ? For eg:-

Type type = GenerateType(myString);

I have to pass this type variable to my further piece of code so please help me to create class/type from the string containing the class definition.


Solution

  • You can use the CSharpCodeProvider to compile your result at runtime and then use the Activator - Class to create an object from your generated code.

    // compile your piece of code to dll file
    Microsoft.CSharp.CSharpCodeProvider cSharpCodeProvider = new Microsoft.CSharp.CSharpCodeProvider();
    System.CodeDom.Compiler.CompilerParameters compilerParameters = new System.CodeDom.Compiler.CompilerParameters();
    compilerParameters.GenerateInMemory = true;
    compilerParameters.GenerateExecutable = false;
    System.CodeDom.Compiler.CompilerResults cResult = cSharpCodeProvider.CompileAssemblyFromSource(compilerParameters, "using System; namespace Tables { 'put here your class definition' }");
    
    // then load your dll file, get type and object from class
    Assembly assembly = cResult.CompiledAssembly;
    Type myTableType = assembly.GetType("Tables.Tablename");
    var finalResult = Activator.CreateInstance(myTableType);