Question

I'm trying do some smart event handling in C#, but I'm stuck with an error message saying :

Cannot implicitly convert type 'System.EventHandler' to xxxxCompletedEventHandler

I have a piece of code that looks like this :

_ServiceAgentArt.Test((s,e) => _List = e.ListOfDTOArt, new DTOArt { Gruppe_id = 1700 });

And in the method Test in the class ServiceAgentArt I have the following code:

public delegate void getArterCompletedEventHandler(getArterCompletedEventArgs e);
public class getArterCompletedEventArgs : EventArgs
{
    public List<DTOArt> ListOfDTOArt { get; set; }
}

sealed class ServiceAgentArt : ServiceAgentBase
{
    public event getArterCompletedEventHandler EventGetArterCompleted;

    public void Test(EventHandler<getArterCompletedEventArgs> e, DTOArt _DTOArt)
    {
        EventGetArterCompleted += e;
        this.GetFromWEBAPI(string.Format("/apiart/getarter?id={0}", _DTOArt.Gruppe_id));
    }

    protected override void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {
        if (EventGetArterCompleted != null)
            EventGetArterCompleted(new getArterCompletedEventArgs { ListOfDTOArt = e.Result.DecodeJSONFromStream<List<DTOArt>>() });
    }
}

But .Net doesn't like the code line EventGetArterCompleted += e;, I fully understand what it tries to tell me, that eventargs can't be casted to eventhandler.

I'm surely missing something here, is there a way to add the eventhandler e to the delegate EventGetArterCompleted ????

Thanks in advance and have a happy weekend :-)

Thomas, Copenhagen, Denmark

Was it helpful?

Solution

When comparing the two signatures:

public delegate void EventHandler<TEventArgs>(Object sender, TEventArgs e);
public delegate void getArterCompletedEventHandler(getArterCompletedEventArgs e);

You can see that the only real difference (with your TEventArgs) is that one has a sender, the other does not. Assuming you really want to use these two separate delegate types, you can do this to make it work, by passing in a null sender.

EventGetArterCompleted += ea => e(null, ea);

Or if your ServiceAgentArt instance should be the sender:

EventGetArterCompleted += ea => e(this, ea);

It might make more sense to only use EventHandler<getArterCompletedEventArgs>, and remove your delegate type.

OTHER TIPS

Your event is obviously not of the EventHandler<TEventArgs> type, but a custom delegate you've defined. Either re-define the event to use EventHandler<TEventArgs> or make the parameter of your method getArterCompletedEventHandle.

In C#, any delegate can only be cast to Delegate or MulticastDelegate types, as they are implicit base of any other delegate, like object is implicit base of any type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top