Delegate.DynamicInvoke for .NET Compact Framework

As you might already know I’m a certified windows mobile application developer. My speciality is hybrid application development for applications which target both the full .NET framework platform and also the mobile platform. Of course nobody wants to write the same code for each platform again so you have to come up with some tricks and solutions to overcome some limitations on the compact framework.

One such limitation is the missing Delegate.DynamicInvoke method. The Delegate.DynamicInvoke method allows to dynamically invoke delegates late-bound. That means normally when you are invoking a method via a delegate you actually need to have knowledge about the target type where the delegate gets executed. With Delegate.DynamicInvoke this is not longer necessary. The beauty of this is, that you can have base code like the following:

// Elsewhere
RegisterDelegate(SomeClass.SomeMethod);
RegisterDelegate(SomeOtherClass.SomeOtherMethod);
FireForAllWith(1, 2, 3, 4);

// Code in some utility
public void FireForAllWith(params object[] args)
{
   someGenericCollection.ForEach(dlg => dlg.DynamicInvoke(args));
}
public void RegisterDelegate(Delegate dlg)
{
   someGenericCollection.Add(dlg);
}

But if you try to use Delegate.DynamicInvoke in the compact framework your infrastructure code will not compile because for some obscure reasons microsoft decided not to implement Delegate.DynamicInvoke for .NET compact framework. Here is my solution to this problem:

I created an extension method for the delegate class with the name DynamicInvoke. This extension method uses a small trick to implement the DynamicInvoke behaviour of the full framework platform.

public static class DelegateExtensions
    {
        public static object DynamicInvoke(this Delegate dlg, params object[] args)
        {
            return dlg.Method.Invoke(dlg.Target, BindingFlags.Default, null, args, null);
        }
    }

As you can see I’m using the delegates method property which returns a MethodInfo object. On the MethodInfo I’m able to call Invoke and pass the arguments to the bound method. But the problem here is that Invoke requires a target where the method gets executed. This is where the delegates target property comes into play. That’s the whole magic and you’re able to dynamically invoke late bound methods via Delegate.DynamicInvoke.

Download DelegateExtensions for the source code.

About the author

Daniel Marbach

5 comments

By Daniel Marbach

Recent Posts