Blog Archive

Friday, June 30

Cast Delegate

Following my previous post, Ed went ahead and made a (C# 2.0-usable) Multicast-capable version:

public static T CastDelegate<T>(Delegate source)
    where T : class
{
    if (source == null)
        return null;

    Delegate[] delegates = source.GetInvocationList();
    if (delegates.Length == 1)
        return Delegate.CreateDelegate(typeof(T), delegates[0].Target, delegates[0].Method) as T;

    for (int i = 0; i < delegates.Length; i++)
        delegates[i] = Delegate.CreateDelegate(typeof(T), delegates[i].Target, delegates[i].Method);
 
    return Delegate.Combine(delegates) as T;
}

1 comment:

Anonymous said...

AHAHA! Thank you very much! I've spent so long looking for this. I'm trying to cache a dictionary of strongly typed property accessor DynamicMethod delegates, and of course the only solution I've had till now was to box and cast everything as Object. This is a breakththrough that will allow me to dump the boxing on the value types! THANK YOU FOR SHARING THIS! seriously I'be been driving myself completely nuts over it.