title: C# Call and return an object from a static method in IL
body: <p>This is an extension to the solutions offered <a href="https://stackoverflow.com/questions/9606104/using-c-sharp-opcodes-to-emit-method-that-returns-an-object">here</a>.  I've created a static method that returns me an object.  My goal, is the write a dynamic method for a type I define at runtime to return me the object that this static method is returning. My code thus far:</p>
  
  <pre><code> // type builder and other prep stuff removed for sake of space and reading
  
  private void EmitReferenceMethodBody(Type returnType)
  {
      MethodBuilder builder =
      typeBuilder.DefineMethod(
                      method.Name,
                      MethodAttributes.Virtual | MethodAttributes.Public,
                      method.CallingConvention,
                      method.ReturnType,
                      typeArray1);
      builder.InitLocals = true;
      ILGenerator gen = builder.GetILGenerator();
      MethodInfo getStoredObject = typeof(ObjectStore).GetMethod("GetStoredObject",                  BindingFlags.Public | BindingFlags.Static);        
      MethodInfo getTypeFromHandle = typeof(Type).GetMethod("GetTypeFromHandle");            
  
      gen.Emit(OpCodes.Ldtoken, returnType);
      gen.Emit(OpCodes.Call, getTypeFromHandle);
      gen.Emit(OpCodes.Call, getStoredObject);
      gen.Emit(OpCodes.Ret);   
  }
  </code></pre>
  
  <p>The updated code now calls the method but appears to be passing the type of the dynamically created type rather then the variable returnType.</p>