Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic EventArgs for built-in types

Posters at Are EventArg classes needed now that we have generics and Does .NET have a built-in EventArgs<T>? are advising against a generic EventArgs, at least that's the feeling I get.

Is it justified to use it when all I need is one of the build-in types? In my specific case I'm reading from a stream over TCP, and when data is received, subscribers are notified.

public event EventHandler<EventArgs<string>> data_received = delegate { };

...

while (!reader.EndOfStream)
{
    if ((data = reader.ReadLine()) != "")
    {
        this.data_received(this, new EventArgs<string>(data));
    }
}

Or perhaps an event isn't the best way to pass data to subscribers?

like image 885
user247702 Avatar asked Mar 11 '12 11:03

user247702


1 Answers

Short answer: it depends.

You can consider EventArgs<T> class like Tuple<T> for passing and returing data to/from the method. In some simple cases and for internal usage Tuple<T> is appropriate but for more complex cases or for public surface it would be more appropriate to use separate type.

With EventArgs<T> we have more or less the same dilema. For internal usage its OK to use this type, but for public API it could lead to maintainance nightmare.

In your particular case it seems OK to use EventArgs<T> at the first glance, but what if later you'll decide to add some additional information to this even like EndPoint? In this case you can use EventArgs<T, U> (like Tuple<T, U>) or you can switch to custom EventArgs class. In both case you'll break all your clients and if you only one client of this code - its ok, but if not...

Bottom line, for internal stuff its ok to use EventArgs, but for public surface I suggest to use custom event args.

P.S. General naming convention for events is CamelCase, and in your particular case it means that DataReceived is more appropriate name for your event.

like image 171
Sergey Teplyakov Avatar answered Nov 03 '22 04:11

Sergey Teplyakov