0

My method to run once the desired event happens is this:

protected virtual void RunThisMethod<T>(object sender, CustomEventArgs<T> e)
        where T : IMyInterface
    {
        //Do something
    }

When I subscribe to the event:

eventSource.SomeEvent += RunThisMethod;

I get the error.

The type arguments for method 'RunThisMethod<T>(object, CustomEventArgs<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

How do I provide IMyInterface while doing subscription? Or am I making some fundamental mistake?

EDIT: The event is defined as:

event EventHandler<CustomEventArgs> SomeEvent ;
NotAgain
  • 1,927
  • 3
  • 26
  • 42
  • What is the signature of `eventSource.SomeEvent`? i.e., is it a generic event (does such a thing exist?)? – Wai Ha Lee Apr 24 '15 at 06:29
  • I updated the question with event signature. Not very clear on events and delegates. They are the "pointers of C" equivalent to me in dot net world. – NotAgain Apr 24 '15 at 06:34
  • Thank you. It looks like you have answers. I did some research and to answer my own question, yes, you *can* have generic events, e.g. [this question](http://stackoverflow.com/q/3126886/1364007). – Wai Ha Lee Apr 24 '15 at 06:37
  • 1
    @WaiHaLee You actually cannot have generic events. In the question you quoted involved a normal event typed with a type parameter from the surrounding class, not a type parameter of the event. The latter must not exist since it would break the type system, actually the same reason why generic field cannot exist. But as said, this is different to using a generic type parameter of a different scope in an event or field. – Georg Apr 24 '15 at 06:57
  • @Georg - Ah - I stand corrected. Thanks for letting me know (and for correcting my blunder). – Wai Ha Lee Apr 24 '15 at 06:59

1 Answers1

0

You need to make sure you declare your event type correctly. You need to specify CustomEventArgs< T > not just CustomEventArgs. Try this:

public class CustomEventArgs<T> : EventArgs
{
    public T CustomArgs { get; set; }
}

public class Example<T>
{
    public Example()
    {
        this.MyEvent += this.Handler;
    }

    public event EventHandler<CustomEventArgs<T>> MyEvent;

    private void Handler(object sender, CustomEventArgs<T> args)
    {

    }
}
James Lucas
  • 2,452
  • 10
  • 15