tags:

views:

77

answers:

3

I've read that one benefit to the MyEventHandler/MyEventArgs model is that it allows standard event handlers to handle a variety of events. It sounds good, but perhaps I'm understanding how this is supposed to work. I have the following code:

public delegate void DataArrivalEventHandler
    (object sender, DataArrivalEventArgs e);

public class DataArrivalEventArgs : EventArgs
{
    public DateTime Arrival { get; protected set; }

    public DataArrivalEventArgs()
    {
        Arrival = DateTime.Now;
    }

    public DataArrivalEventArgs(DateTime arrival)
    {
        Arrival = arrival;
    }
}

...

_pipeReader.DataArrival += new EventHandler(Pipe_DataArrival);

...

private void Pipe_DataArrival(object sender, EventArgs e)
{
    ...
}

The code throws an error when I'm trying to add the event handler, however, saying that it cannot implicity cast DataArrivalEventHandler to EventHandler. Changing DataArrivalEventHandler(Pipe_DataArrival) to EventHandler(Pipe_DataArrival) fixes the problem, so I feel like you should be able to add generic event handlers to more specific events (I understand why you can't do it the other way around.)

Is how I have it the best way to do it, or is there a better convention?

A: 

The way you've got it is right.

There's no conversion from a more specific delegate type to a more general one - but there is a conversion from a method group with a more specific set of parameters to a delegate type with a more general set of parameters. (It works the other way for return types.)

Now C# 4 changes this slightly, as there is a conversion from (say) Action<string> to Action<object> - but this only happens for generic delegates, in terms of their type parameters.

Jon Skeet
A: 

I think delegate contravariance (assigning EventHandler delegate to DataArrivalEventHandler) does not work in .NET 1.1. It is available since .NET 2.0

(Your code looks like .NET 1.1 code)

STO
This is all C# in .Net 4.0
Daniel Rasmussen
A: 

Naming

There are a naming convention for events. In your case the event should be named DataArrived. Read more here: http://msdn.microsoft.com/en-us/library/h0eyck3s(v=VS.71).aspx

Delegates

You got two delegates for events that should be used: EventHandler and EventHandler<T>

Multihtreading

If you are using multithreading, init your event in the following way.

public event EventHandler<MyEventArgs> = delegate {};

In this way you don't have to worry about multithreading issues.

jgauffin