none
Create Class in C#.net Dynamically in Runtime

    General discussion

  •  

    Hi

    I have critical requirement did any have experience on this problem please help out!

    Class Name: RuntimeClass

    public class RuntimeClass
    {
        private int GenClass_id;
        private string fname;
        private string lname;

    ----- Constructor
        public RuntimeClass()
        {
            id = new.Guid();
        }
        
       public int GenClass_ID
        {
          get{return GenClass_iD;}
        }
        
        public string FirstName
        {
            Get{ return this.fname;}
            Set{fname = value;}
        }

        public string LastName
        {
            Get{ return this.lname;}
            Set{fname = value;}
       }  

    }


    i need to Generate class using dynamically in runtime

    how to generate the class runtime did any one have the solution for this?


    kind regards
    orcas
    Orcas
    Monday, July 28, 2008 11:24 AM

All replies

  • Do you mean that you want to dynamically construct a class definition in memory (as a string), and then compile and use it?

    Assuming that's true: I don't have any code that does exactly what you want, but I do have a sample where I dynamically create a class and construct an instance of it. This sample shows how to dynamically evaluate expressions, but it creates a class as part of its implementation.

    In case it's of interest, here it is (a console app):

    using System; 
    using System.Reflection; 
    using System.CodeDom.Compiler; 
     
    using Microsoft.CSharp; 
     
     
    /// <summary>This simple program demonstrates how to dynamically compile code.</summary> 
     
     
    class Program 
        static void Main() 
        { 
            TestExpression("2+1-(3*2)+8/2"); 
            TestExpression("1*2*3*4*5*6"); 
            TestExpression("Invalid expression"); 
        } 
     
        static void TestExpression(string expression) 
        { 
            try 
            { 
                int result = EvaluateExpression(expression); 
                Console.WriteLine("'" + expression + "' = " + result); 
            } 
     
            catch (Exception) 
            { 
                Console.WriteLine("Expression is invalid: '" + expression + "'"); 
            } 
        } 
     
        public static int EvaluateExpression(string expression) 
        { 
            string code = string.Format  // Note: Use "{{" to denote a single "{" 
            ( 
                "public static class Func{{ public static int func(){{ return {0};}}}}", 
                expression 
            ); 
     
            CompilerResults compilerResults = CompileScript(code); 
     
            if (compilerResults.Errors.HasErrors) 
            { 
                throw new InvalidOperationException("Expression has a syntax error."); 
            } 
     
            Assembly assembly = compilerResults.CompiledAssembly; 
            MethodInfo method = assembly.GetType("Func").GetMethod("func"); 
     
            return (int)method.Invoke(null, null); 
        } 
     
        public static 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); 
        } 
     



    Monday, July 28, 2008 11:52 AM
  • Outstanding!  I was browsing Google and found this code.  It fits exactly to what I was looking for to build dynamic functionality on the fly.  Thanks for sharing.
    Wednesday, August 10, 2011 3:42 PM
  • Hi Matthew,

    This is not at all what I was looking for, but I found it so interesting I felt I had to comment and congratulate you on your solution. I'm sure it will help me out at some stage in the future. As Rick mentioned, thanks for sharing.

    Kind regards,

     

     

    Kaine

    Tuesday, October 11, 2011 9:48 AM
  • hi, i have used code its gud one,but i have one doubt regarding this code,what is that , i need to create one property class and set and get value from this is it possible ? [eg:"public class Func{private string myCaption;public string _LeadType{get { return myCaption; }set {myCaption = value;}}}"]
    Tuesday, June 19, 2012 11:02 AM
  • It should work. You can use GetProperty instead of GetMethod and call GetValue and SetValue.

    Tuesday, June 19, 2012 3:34 PM
  • Hi Lois,

              I have facing some issue on GetValue and SetValue Funtions here is my Code,

    string code = "public class Func{private string myCaption;public string _LeadType{get { return myCaption; }set {myCaption = value;}}}";
           CompilerResults compilerResults = CompileScript(code);
            if (compilerResults.Errors.HasErrors)
            {
                Response.Write(compilerResults.Errors.ToString());
            }
            Assembly assembly = compilerResults.CompiledAssembly;      
            PropertyInfo pinfo = assembly.GetType("Func").GetProperty("_LeadType");

     can you share me the code how do the SetValue function.?

    Wednesday, June 20, 2012 5:58 AM
  • It's not a static property, so you need an instance.

    object instance = Activator.CreateInstance(assembly.GetType("Func"));
    pinfo.SetValue(instance, value, null);
    object value = pinfo.GetValue(instance, null);

    Wednesday, June 20, 2012 3:23 PM
  • Thanks its working fine, i want to know more that how save this class as [Func.cs] is it possible ?
    Thursday, June 21, 2012 7:27 AM
  • hi, i created one class with like this, and could'nt compiled properly its throwing error like CS0234

    using System;
    using System.Runtime.InteropServices;
    using System.Globalization;
    using System.Collections.Generic;
    namespace Service
    {

          public class Functions
        {
            public Functions()
            {

            }
            string strConnection = "@Data Source=5933.56.56.198;Initial Catalog=TestService;Persist Security Info=True;User ID=pp;Password=pwsd";
            System.Data.SqlClient.SqlConnection cnn;
        }

    }



    • Edited by SujilKumar Friday, June 22, 2012 10:53 AM
    Friday, June 22, 2012 10:53 AM
  • Maybe you need to add a reference to System.Data.dll to your project.

    Monday, June 25, 2012 3:29 PM
  • its throwing One error like this

    The type or namespace name 'Data' does not exist in the namespace 'System' (are you missing an assembly reference?)

    Tuesday, June 26, 2012 10:42 AM
  • Hi Suhil,

    I think you need add below code

    parms.ReferencedAssemblies.Add("System.dll");
    parms.ReferencedAssemblies.Add("System.Data.dll");

    Something like below:

    public static CompilerResults CompileScript(string source)
    {
    	CompilerParameters parms = new CompilerParameters();
    	parms.GenerateExecutable = false;
    	parms.GenerateInMemory = true;
    	parms.IncludeDebugInformation = false;
    	parms.ReferencedAssemblies.Add("System.dll");
    	parms.ReferencedAssemblies.Add("System.Data.dll");
    	CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp");
    	return compiler.CompileAssemblyFromSource(parms, source);
    }


    • Edited by Vic Vega Tuesday, June 26, 2012 11:11 AM
    Tuesday, June 26, 2012 11:10 AM
  • good example. thanks
    Monday, March 25, 2013 10:01 AM
  • I am trying to use the above example, but my code does not recognize CompilerResults class, although I'm using System.CodeDom.Compiler namespace.

    Does any of you has any suggestions?

    Thanks

    P.S. my application is a silverlight application
    • Edited by cc oo Tuesday, October 01, 2013 6:48 AM
    Tuesday, October 01, 2013 6:16 AM