void PrintPropertyInfo(DynamicProperty dp)
 {
     Debug.WriteLine(String.Format("Building Property {0} of Type {1}", dp.Name, dp.Type.Name));
 }
        FieldInfo[] GenerateProperties(TypeBuilder tb, DynamicProperty[] properties, Type returnType = null)
        {
            FieldInfo[] fields = new FieldBuilder[properties.Length];
            for (int i = 0; i < properties.Length; i++)
            {
                DynamicProperty dp = properties[i];
                PrintPropertyInfo(dp);
                FieldBuilder    fb = tb.DefineField("_" + dp.Name, dp.Type, FieldAttributes.Private);
                PropertyBuilder pb = tb.DefineProperty(dp.Name, PropertyAttributes.HasDefault, dp.Type, null);

                if (dp.CustomAttributeBuilder != null)
                {
                    pb.SetCustomAttribute(dp.CustomAttributeBuilder);
                }



                MethodBuilder mbGet = tb.DefineMethod("get_" + dp.Name,
                                                      MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Virtual,
                                                      dp.Type, Type.EmptyTypes);
                ILGenerator genGet = mbGet.GetILGenerator();
                genGet.Emit(OpCodes.Ldarg_0);
                genGet.Emit(OpCodes.Ldfld, fb);
                genGet.Emit(OpCodes.Ret);

                if (returnType != null)
                {
                    var returnTypeMi = returnType.GetMethod(mbGet.Name);

                    if (returnTypeMi != null)
                    {
                        tb.DefineMethodOverride(mbGet, returnTypeMi);
                    }
                }

                MethodBuilder mbSet = tb.DefineMethod("set_" + dp.Name,
                                                      MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Virtual,
                                                      null, new Type[] { dp.Type });
                ILGenerator genSet = mbSet.GetILGenerator();
                genSet.Emit(OpCodes.Ldarg_0);
                genSet.Emit(OpCodes.Ldarg_1);
                genSet.Emit(OpCodes.Stfld, fb);
                genSet.Emit(OpCodes.Ret);

                if (returnType != null)
                {
                    var returnTypeMi = returnType.GetMethod(mbSet.Name);

                    if (returnTypeMi != null)
                    {
                        tb.DefineMethodOverride(mbSet, returnTypeMi);
                    }
                }

                pb.SetGetMethod(mbGet);
                pb.SetSetMethod(mbSet);



                fields[i] = fb;
            }
            return(fields);
        }