tags:

views:

86

answers:

3

Hi,

I have a generic method that has some parameter of a generic Type. What I want to do, is be able to access the method on this generic type parameter inside my function.

    public void dispatchEvent<T>(T handler, EventArgs evt)
        {
            T temp = handler; // make a copy to be more thread-safe
            if (temp != null)
            {
                temp.Invoke(this, evt);
            }
        }

I want to be able to call the Invoke method on temp, which is of type T. Is there a way to do this?

Thank You.

+5  A: 

Use a constraint for the generic:

public void dispatchEvent<T>(T handler, EventArgs evt) where T : yourtype
spinon
I doubt this works with a delegate type as `yourtype`.
dtb
A: 

How about this :

    public void dispatchEvent<T>(T handler, EventArgs evt)
    {
        T temp = handler; // make a copy to be more thread-safe
        if (temp != null && temp is Delegate)
        {
            (temp as Delegate).Method.Invoke((temp as Delegate).Target, new Object[] { this, evt });
        }
    }
decyclone
+2  A: 

You might be after something more like:

        public void dispatchEvent<T>(EventHandler<T> handler, T evt) 
            where T: EventArgs
        {
            if (handler != null)
                handler(this, evt);
        }

Just for fun, here it is as an extension method:

    public static void Raise<T>(this EventHandler<T> handler, Object sender, T args)
        where T : EventArgs
    {
        if (handler != null)
            handler(sender, args);
    }
Dan Bryant
+1 (except for the method body)
dtb
@dtb, Thanks, missed that. Got rid of the local copy while I was at it, since it's pointless in this case (already copied in parameter.)
Dan Bryant
Yep, this did the trick. Have no idea what extension methods are though?!?
didibus
@didibus: Have a look at http://msdn.microsoft.com/en-us/library/bb383977.aspx I'm not sure if extension methods work with `event` members though.
dtb