strange way to subscibe to an event without explicitly using the EventHandler

T

Tony Johansson

Hi!

Below is a snippet of a class Test
Normally when you use events and want to subscribe to an event you use
statement like this
timer.Tick += new EventHandler(t_Tick);
In the class below you can subscribe to an event by writing this statement
timer.Tick += t_Tick;
instead and skip the delegate EventHandler and it works and I'm very
surprised.

So can somebody explain why it't possible to subscribe to an event by using
this statement
timer.Tick += t_Tick;

public partial class Test : Form
{
private Timer timer;

public Test()
{
timer = new Timer();
timer.Interval = 1000;
//timer.Tick += new EventHandler(t_Tick);
timer.Tick += t_Tick;
timer.Start();
}

void t_Tick(object sender, EventArgs e)
{
//some code here
}

//Tony
 
G

Göran Andersson

Tony said:
Hi!

Below is a snippet of a class Test
Normally when you use events and want to subscribe to an event you use
statement like this
timer.Tick += new EventHandler(t_Tick);
In the class below you can subscribe to an event by writing this statement
timer.Tick += t_Tick;
instead and skip the delegate EventHandler and it works and I'm very
surprised.

So can somebody explain why it't possible to subscribe to an event by using
this statement
timer.Tick += t_Tick;

public partial class Test : Form
{
private Timer timer;

public Test()
{
timer = new Timer();
timer.Interval = 1000;
//timer.Tick += new EventHandler(t_Tick);
timer.Tick += t_Tick;
timer.Start();
}

void t_Tick(object sender, EventArgs e)
{
//some code here
}

//Tony

Because the compiler adds the construction of the EventHandler when you
add a delegate to an event. It's just a shortcut, the generated code is
the same.
 
T

Tom Shelton

Hi!

Below is a snippet of a class Test
Normally when you use events and want to subscribe to an event you use
statement like this
timer.Tick += new EventHandler(t_Tick);
In the class below you can subscribe to an event by writing this statement
timer.Tick += t_Tick;
instead and skip the delegate EventHandler and it works and I'm very
surprised.

So can somebody explain why it't possible to subscribe to an event by using
this statement
timer.Tick += t_Tick;

public partial class Test : Form
{
private Timer timer;

public Test()
{
timer = new Timer();
timer.Interval = 1000;
//timer.Tick += new EventHandler(t_Tick);
timer.Tick += t_Tick;
timer.Start();
}

void t_Tick(object sender, EventArgs e)
{
//some code here
}

//Tony


That is a feature added in the C# 2.0 language - the compiler infers the type
of the delegate and does the construction for you.
 

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