Dealing with generic nested types

by Geert 29. December 2011 15:50

Recently I was working on true weak actions and wanted to do something like this:

   1: public class WeakAction<TParameter>
   2: {
   3:     public delegate void OpenInstanceGenericAction<TTarget>(TTarget @this, TParameter parameter);
   4:  
   5:     public WeakAction(object target, Action<TParameter> action)
   6:     {
   7:         var targetType = (target != null) ? target.GetType() : typeof(object);
   8:         var delegateType = typeof(OpenInstanceGenericAction<>).MakeGenericType(targetType, typeof(TParameter));
   9:  
  10:         _action = Delegate.CreateDelegate(delegateType, null, action.Method);
  11:     }
  12: }

I was pretty sure I was doing it all right. In this code, I create a generic open instance handler to make sure I can invoke the method without referencing the instance itself. This allows me to write true weak actions.

Anyway, the error that pops up is:

System.ArgumentException: Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.

Scratching my head over and over again, for about 1 hour, something came into my mind that couldn’t be true: would it be that I have to define the TParameter first, and then the TTarget, even when the delegate uses them in another order?

The answer seemed to be yes!

Apparently, you need to specify the order of arguments. So, because the delegate is part of a class defining the first generic argument (TParameter), you need to specify that first. So, it is not the order in which they are used inside the delegate, but the order of definition.

Tags:

C# | Catel

Comments are closed

About the Author

Geert van Horrik is a independent freelance software developer since January 1st, 2007. Since then he was been working on several projects from C++ to C# (WPF, ASP.NET, etc). Currently he loves to write his software using WPF (or Silverlight if WPF isn't an option).

Lately, Geert is spending a lot of time on Catel, a free open-source MVVM Framework for WPF and Silverlight. Actually, it's more than "just" an MVVM Framework, it's a complete application library!