2006-12-27

Delegates

I just remembered another technique for calling methods discovered via reflection! It is possible to convert a MethodInfo to a delegate and call it, this is just as fast as calling the method directly. So if you have a method that you call often which was discovered via reflection you should try this....

private delegate bool DoSomethingDelegate(object a, object b);

MethodInfo methodInfo = type.GetMethod(.........);
DoSomethingDelegate method =
(DoSomethingDelegate)
Delegate.CreateDelegate(typeof(DoSomethingDelegate), methodInfo);

for (int i = 0; i < 1000000, i++)
method(this, this);

2 comments:

Anonymous said...

Thanks so much. Exactly what I needed.

Anonymous said...

Whats the .NetCF Equivalent?