Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 567
Ankur Arora Avatar asked Oct 26 '25 15:10

Ankur Arora


1 Answers

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);
like image 92
Craylen Avatar answered Oct 29 '25 06:10

Craylen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!