Vahid Farahmandian Vahid Farahmandian - 2 years ago 132 Question

Create Class dynamically at runtime

i have method like this: (this is a generic method, and DYNAMIC_CLASS_TYPE will be changed in situation to other situation)

Dim res = f.MyMethod(Of DYNAMIC_CLASS_TYPE)("select Id, Name from myTable")

I want to create a dynamic class based on my queries columns and then pass the class instead of DYNAMIC_CLASS_TYPE.
How can I do this?

Answer Source

I finally succeeded in doing it. My Code is as:

 Public Shared Function CreateClass(ByVal className As String, ByVal properties As Dictionary(Of String, Type)) As Type

    Dim myDomain As AppDomain = AppDomain.CurrentDomain
    Dim myAsmName As New AssemblyName("MyAssembly")
    Dim myAssembly As AssemblyBuilder = myDomain.DefineDynamicAssembly(myAsmName, AssemblyBuilderAccess.Run)

    Dim myModule As ModuleBuilder = myAssembly.DefineDynamicModule("MyModule")

    Dim myType As TypeBuilder = myModule.DefineType(className, TypeAttributes.Public)


    For Each o In properties

        Dim prop As PropertyBuilder = myType.DefineProperty(o.Key, PropertyAttributes.HasDefault, o.Value, Nothing)

        Dim field As FieldBuilder = myType.DefineField("_" + o.Key, GetType(Integer), FieldAttributes.[Private])

        Dim getter As MethodBuilder = myType.DefineMethod("get_" + o.Key, MethodAttributes.[Public] Or MethodAttributes.SpecialName Or MethodAttributes.HideBySig, o.Value, Type.EmptyTypes)
        Dim getterIL As ILGenerator = getter.GetILGenerator()
        getterIL.Emit(OpCodes.Ldfld, field)

        Dim setter As MethodBuilder = myType.DefineMethod("set_" + o.Key, MethodAttributes.[Public] Or MethodAttributes.SpecialName Or MethodAttributes.HideBySig, Nothing, New Type() {o.Value})
        Dim setterIL As ILGenerator = setter.GetILGenerator()
        setterIL.Emit(OpCodes.Stfld, field)



    Return myType.CreateType()

End Function

The return value of the function is a Type of my Custom Class. Thank you all for participation

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download