How to specify an event handler
-
If I have a class with an event, and a class that wants to attach to the handler:
class A
{
public event EventHandler SomeEvent;
}class B
{
public void AttachToHandler(A a)
{
a.SomeEvent += ***; // << here's my question
}void SomeEventHandler(object sender, SomeEventArgs e) {... }
}
The VC# Express IDE ("press TAB to insert..") suggests:
a.SomeEvent += new EventHandler(SomeEventHandler);
However, the following also seems to work:
a.SomeEvent += SomeEventHandler;
Now the questions: Is there a difference between the two? A "preferred style"?
We are a big screwed up dysfunctional psychotic happy family - some more screwed up, others more happy, but everybody's psychotic joint venture definition of CP
My first real C# project | Linkify!|FoldWithUs! | sighist -
If I have a class with an event, and a class that wants to attach to the handler:
class A
{
public event EventHandler SomeEvent;
}class B
{
public void AttachToHandler(A a)
{
a.SomeEvent += ***; // << here's my question
}void SomeEventHandler(object sender, SomeEventArgs e) {... }
}
The VC# Express IDE ("press TAB to insert..") suggests:
a.SomeEvent += new EventHandler(SomeEventHandler);
However, the following also seems to work:
a.SomeEvent += SomeEventHandler;
Now the questions: Is there a difference between the two? A "preferred style"?
We are a big screwed up dysfunctional psychotic happy family - some more screwed up, others more happy, but everybody's psychotic joint venture definition of CP
My first real C# project | Linkify!|FoldWithUs! | sighistI've always used the first method (using the New operator to instantiate a new delegate that will handle the event). You can alway declare a variable that holds the reference to the event handler in advance and then use that as your handler like so:
EventHandler eh; eh = **New** EventHandler(SomeEventHandler); a.SomeEvent += eh;
this way you could later detach the event handler too, like so:a.SomeEvent -= eh; _//(as long as eh still references your event handler!)_
The second way seems to be a shortcut for the first (in which the compiler automatically generates the code that instantiated the delegate and than passes it your function). Hope this helps, but your best bet is to do some reading on delegates and event handlers in C#.---- www.digitalGetto.com