Wednesday, November 21, 2007

DynamicInvoke

Dynamic invoke is the method that allows you to Invoke a delegate of a type you don't know at runtime (uses some reflection inside).

A good thing to use as a pattern is to invoke a Delegate d as:

try
{
d.DynamicInvoke();
}
catch (System.Reflection.TargetInvocationException ex)
{
HandleException(ex);
}

where handleexception does:

void HandleException(Exception ex)
{
if (ex != null && ex.InnerException != null)
throw ex.InnerException;
if (ex != null)
throw ex;
throw new Exception("Unhandled exception");
}

Meaning it rethrows the innerexception to the application, instead of the boxed one.

No comments: