ILCode for newobj by creating a new custom Type

AssemblyName _assemblyName = new AssemblyName();
_assemblyName.Name = "newObj";
AssemblyBuilder _assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(_assemblyName, AssemblyBuilderAccess.RunAndSave);
ModuleBuilder _modBuilder = _assemblyBuilder.DefineDynamicModule(_assemblyName.Name + ".exe");
TypeBuilder _typeBuilder = _modBuilder.DefineType(" ILCode.Program");

TypeBuilder _customType = _modBuilder.DefineType("ILCode.myCustomType", TypeAttributes.Public);

Type[] arg = { typeof(string) };
ConstructorBuilder _customTypeConstructor = _customType.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, arg);
PropertyBuilder _prop1 = _customType.DefineProperty("MyId", PropertyAttributes.None, typeof(int), new Type[0]);
PropertyBuilder _prop2 = _customType.DefineProperty("MyName", PropertyAttributes.None, typeof(string), new Type[0]);
FieldBuilder _fld1 = _customType.DefineField("Nid", typeof(string), FieldAttributes.Private);

//// Generating Dummy code for myCustomType Constructor /////

ILGenerator _ilSubType = _customTypeConstructor.GetILGenerator();
_ilSubType.Emit(OpCodes.Ldarg_0);
_ilSubType.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes));
_ilSubType.Emit(OpCodes.Ldarg_0);
_ilSubType.Emit(OpCodes.Ldarg_1);
_ilSubType.Emit(OpCodes.Stfld, _fld1);
_ilSubType.EmitWriteLine(_fld1);
_ilSubType.Emit(OpCodes.Ret);

//// Generating Code for instantiating myCustomType /////
MethodBuilder _methodBuilder = _typeBuilder.DefineMethod("Main", MethodAttributes.Static, typeof(void), System.Type.EmptyTypes);
ILGenerator _il = _methodBuilder.GetILGenerator();
LocalBuilder _local1 = _il.DeclareLocal(_customType.CreateType());
_il.Emit(OpCodes.Nop);
_il.Emit(OpCodes.Ldstr, "Object Instantiated!");
_il.Emit(OpCodes.Newobj, _customTypeConstructor);
_il.Emit(OpCodes.Stloc_0);
_il.Emit(OpCodes.Ret);

_typeBuilder.CreateType();

_modBuilder.CreateGlobalFunctions();
_assemblyBuilder.SetEntryPoint(_methodBuilder, PEFileKinds.ConsoleApplication);
_assemblyBuilder.Save(_assemblyName.Name + ".exe");
_il = null;

Comments

Popular posts from this blog

The specified initialization vector (IV) does not match the block size for this algorithm