Cook Computing

Delegate Types via Reflection.Emit

February 17, 2004 Written by Charles Cook

Using a C# delegate the other day I thought it would be useful if it was unnecessary to define delegate types manually, for example if an assembly you're using also provided delegate types for all the methods you might call. This seemed like something that could be generated automatically via Reflection.Emit and a Google search quickly threw up an interesting blog entry by Joal Pobar which describes how to do this. Joal's code could be wrapped up in a tool which could be used in your build process to generate delegate types for specific interfaces or classes.

If you want to use a generated delegate asynchronously you need to also generate the BeginInvoke and EndInvoke methods, as in the following additional code:


Type[] paramTypes2 = new Type[parameters.Length+2];
for (int j = 0; j < parameters.Length; j++)
{
	paramTypes2[j] = parameters[j].ParameterType;
}
paramTypes2[parameters.Length] = typeof(AsyncCallback);
paramTypes2[parameters.Length+1] = typeof(object);
methodBuilder = typeBuilder.DefineMethod("BeginInvoke", 
  MethodAttributes.Public | MethodAttributes.HideBySig 
    | MethodAttributes.NewSlot | MethodAttributes.Virtual, 
  typeof(IAsyncResult), paramTypes2);
methodBuilder.SetImplementationFlags(MethodImplAttributes.Runtime 
  | MethodImplAttributes.Managed);

Type[] paramTypes3 = new Type[1];
paramTypes3[0] = typeof(IAsyncResult);
methodBuilder = typeBuilder.DefineMethod("EndInvoke", 
  MethodAttributes.Public | MethodAttributes.HideBySig 
    | MethodAttributes.NewSlot | MethodAttributes.Virtual, 
  targetMethod.ReturnType, paramTypes3);
methodBuilder.SetImplementationFlags(MethodImplAttributes.Runtime 
  | MethodImplAttributes.Managed);