EventArgs design question

L

Leslie Sanford

I have a hierarchy of message classes. Many times when messages are
created/received by a class, an event is generated to let the outside
know. Also, the message is passed along when raising the event.

To follow the .NET event guidelines, each message class therefore needs
its own EventArgs derived class to represent it. The problem is that
these EventArgs classes do not add anything of value themselves. There
is no additional event data they can contain other than the message
itself.

So I was thinking about replacing the message classes with the EventArgs
classes. In other words, put all of the properties and methods that are
in the message classes into the EventArgs classes. Since the message
classes are small and immutable, I don't see any negative side-effects
from doing this.

The problem is that there are times when you need a message class object
that is not the result of an event. In those situations, you would be
working with an EventArgs object when no event has occurred. That seems
a little strange.

This is all a matter of design and convention. Seems like in my desire
to follow guidelines, I'm lead to a compromise that's less than optimum.

At any rate, I was happy to see the generic EventHandler<TEventArgs> in
the latest version of the .NET Framework. I can see reasons against
this, but a generic EventArgs<TEventData> class might come in handy
here, too.
 
K

Kevin Spencer

Hi Leslie,

The EventArgs class was designed to be inherited. It doesn't contain any
public data. When you inherit it, you provide the derived class with your
own data. In your case, your Message class would be the data.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
You can lead a fish to a bicycle,
but it takes a very long time,
and the bicycle has to *want* to change.
 
M

Marc Gravell

As an aside - I use the following quite a bit:

[System.ComponentModel.ImmutableObject(true)]
public class SimpleEventArgs<T> : EventArgs {
private readonly T _value;
public T Value { get { return _value; } }
public SimpleEventArgs(T message) {
_value = message;
}
}


public event EventHandler<SimpleEventArgs<string>> SomeEvent;

This allows me to include a single, strongly typed, object (message) in my
event definition at no cost in terms of typing.

Marc
 
M

Marc Gravell

Minor note: param name "message" was unintentional (leftover from
refactoring); should be value.

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top