none
Create Dynamic class at runtime

    Question

  • hi to all 
    can any body have idea for create dynamic class at run time.
    i have onedictionary<string,object> which is contains datatable's all columns with it's datatype 
    my plan is to create a dynamic class base on dictionary. 
    means datatable's column name is property of class.
    after create list<dynamic class> and bind to grid

    it's grate help if you have code for it

    Wednesday, February 08, 2012 5:04 AM

Answers

  • can any body have idea for create dynamic class at run time.

    follow my below code, which will create class with list of class, just the pass the list of columns/properties you need and let me know if anything else needed.

          		
    		private object CreateProperties (AssemblyName assemblyName, List<string> list)
            {
    			AssemblyName assemblyName = new AssemblyName();
    			assemblyName.Name = "IptegoDetailsAssenblyClass";  
                object AudioInObject = null;
                AssemblyBuilder assemblybuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
                ModuleBuilder module = assemblybuilder.DefineDynamicModule("IptegoDetailsModule");
                TypeBuilder typebuilder = module.DefineType("BindableRowCellCollection", TypeAttributes.Public | TypeAttributes.Class);
                try
                {
                    foreach (string str in list)
                    {
                        string propertyName = str;
    
                        // Generate a private field
                        FieldBuilder field = typebuilder.DefineField("_" + propertyName, typeof(string), FieldAttributes.Private);
                        // Generate a public property
                        PropertyBuilder property =
                            typebuilder.DefineProperty(propertyName,
                                             PropertyAttributes.None,
                                             typeof(string),
                                             new Type[] { typeof(string) });
    
                        // The property set and property get methods require a special set of attributes:
    
                        MethodAttributes GetSetAttr =
                            MethodAttributes.Public |
                            MethodAttributes.HideBySig;
    
                        // Define the "get" accessor method for current private field.
                        MethodBuilder currGetPropMthdBldr =
                            typebuilder.DefineMethod("get_value",
                                                       GetSetAttr,
                                                       typeof(string),
                                                       Type.EmptyTypes);
    
                        // Intermediate Language stuff...
                        ILGenerator currGetIL = currGetPropMthdBldr.GetILGenerator();
                        currGetIL.Emit(OpCodes.Ldarg_0);
                        currGetIL.Emit(OpCodes.Ldfld, field);
                        currGetIL.Emit(OpCodes.Ret);
    
                        // Define the "set" accessor method for current private field.
                        MethodBuilder currSetPropMthdBldr =
                            typebuilder.DefineMethod("set_value",
                                                       GetSetAttr,
                                                       null,
                                                       new Type[] { typeof(string) });
    
                        // Again some Intermediate Language stuff...
                        ILGenerator currSetIL = currSetPropMthdBldr.GetILGenerator();
                        currSetIL.Emit(OpCodes.Ldarg_0);
                        currSetIL.Emit(OpCodes.Ldarg_1);
                        currSetIL.Emit(OpCodes.Stfld, field);
                        currSetIL.Emit(OpCodes.Ret);
    
                        // Last, we must map the two methods created above to our PropertyBuilder to 
                        // their corresponding behaviors, "get" and "set" respectively. 
                        property.SetGetMethod(currGetPropMthdBldr);
                        property.SetSetMethod(currSetPropMthdBldr);                   
    
                       
                    }
                    // Generate our type
                    Type generetedType = typebuilder.CreateType();
    
                    // Now we have our type. Let's create an instance from it:
                    AudioInObject = Activator.CreateInstance(generetedType);
                    return AudioInObject;
                }
                catch (Exception ex)
                {
                }
                return AudioInObject;
            }
    Wednesday, February 08, 2012 7:56 AM

All replies

  • can any body have idea for create dynamic class at run time.

    follow my below code, which will create class with list of class, just the pass the list of columns/properties you need and let me know if anything else needed.

          		
    		private object CreateProperties (AssemblyName assemblyName, List<string> list)
            {
    			AssemblyName assemblyName = new AssemblyName();
    			assemblyName.Name = "IptegoDetailsAssenblyClass";  
                object AudioInObject = null;
                AssemblyBuilder assemblybuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
                ModuleBuilder module = assemblybuilder.DefineDynamicModule("IptegoDetailsModule");
                TypeBuilder typebuilder = module.DefineType("BindableRowCellCollection", TypeAttributes.Public | TypeAttributes.Class);
                try
                {
                    foreach (string str in list)
                    {
                        string propertyName = str;
    
                        // Generate a private field
                        FieldBuilder field = typebuilder.DefineField("_" + propertyName, typeof(string), FieldAttributes.Private);
                        // Generate a public property
                        PropertyBuilder property =
                            typebuilder.DefineProperty(propertyName,
                                             PropertyAttributes.None,
                                             typeof(string),
                                             new Type[] { typeof(string) });
    
                        // The property set and property get methods require a special set of attributes:
    
                        MethodAttributes GetSetAttr =
                            MethodAttributes.Public |
                            MethodAttributes.HideBySig;
    
                        // Define the "get" accessor method for current private field.
                        MethodBuilder currGetPropMthdBldr =
                            typebuilder.DefineMethod("get_value",
                                                       GetSetAttr,
                                                       typeof(string),
                                                       Type.EmptyTypes);
    
                        // Intermediate Language stuff...
                        ILGenerator currGetIL = currGetPropMthdBldr.GetILGenerator();
                        currGetIL.Emit(OpCodes.Ldarg_0);
                        currGetIL.Emit(OpCodes.Ldfld, field);
                        currGetIL.Emit(OpCodes.Ret);
    
                        // Define the "set" accessor method for current private field.
                        MethodBuilder currSetPropMthdBldr =
                            typebuilder.DefineMethod("set_value",
                                                       GetSetAttr,
                                                       null,
                                                       new Type[] { typeof(string) });
    
                        // Again some Intermediate Language stuff...
                        ILGenerator currSetIL = currSetPropMthdBldr.GetILGenerator();
                        currSetIL.Emit(OpCodes.Ldarg_0);
                        currSetIL.Emit(OpCodes.Ldarg_1);
                        currSetIL.Emit(OpCodes.Stfld, field);
                        currSetIL.Emit(OpCodes.Ret);
    
                        // Last, we must map the two methods created above to our PropertyBuilder to 
                        // their corresponding behaviors, "get" and "set" respectively. 
                        property.SetGetMethod(currGetPropMthdBldr);
                        property.SetSetMethod(currSetPropMthdBldr);                   
    
                       
                    }
                    // Generate our type
                    Type generetedType = typebuilder.CreateType();
    
                    // Now we have our type. Let's create an instance from it:
                    AudioInObject = Activator.CreateInstance(generetedType);
                    return AudioInObject;
                }
                catch (Exception ex)
                {
                }
                return AudioInObject;
            }
    Wednesday, February 08, 2012 7:56 AM
  • How would you set the property values of the class once you have an instance of the dynamic class created?

    Thursday, March 08, 2012 4:08 PM
  • get the class name and its properties and set the values for each property.

    MyClass class=new MyClass();

    Type type= class.GetType();

    PropertyInfo[] propertyInfo = type.GetProperties();

    foreach(PropertyInfo property in propertyInfo )

    {

      property.SetValue("somevalue",null);

    }

    Friday, March 09, 2012 1:13 AM