Third argument for EventHandler

E

Elliot

How can I pass the value of variable text to t except declare text at class
level?

..........
string text = "text";
Timer a = new Timer();
a.Interval = 10000;
a.Start();
a.Tick += new EventHandler(t);
..........

private void t(object sender, EventArgs eArgs)
{
}
 
N

Nicholas Paldino [.NET/C# MVP]

Elliot,

Well, the way you have it, you can't, as the EventHandler delegate only
takes two parameters.

However, you can make the value text available to t by setting a field
in the class that t is on, and then use it that way.

Or, you can use an anonymous method and change t like so:

private void t(object sender, EventArgs eArgs, string text)
{

}

string text = "text";
Timer a = new Timer();
a.Interval = 10000;
a.Start();
a.Tick += delegate(object sender, EventArgs e) { t(sender, e, text); };

If you are using C# 3.0, you can use a lambda expression as well to make
this code even smaller.
 
M

Marc Gravell

Since you are *handling* an event, you can't use a custom
handler/event-args, but you might be able to do what you want via an
anonymous method:

a.Tick += delegate { SomeMethod(text);}

SomeMethod(string value) {
//...
}

Marc
 
E

Elliot

Works, thank you.


Nicholas Paldino said:
Elliot,

Well, the way you have it, you can't, as the EventHandler delegate only
takes two parameters.

However, you can make the value text available to t by setting a field
in the class that t is on, and then use it that way.

Or, you can use an anonymous method and change t like so:

private void t(object sender, EventArgs eArgs, string text)
{

}

string text = "text";
Timer a = new Timer();
a.Interval = 10000;
a.Start();
a.Tick += delegate(object sender, EventArgs e) { t(sender, e, text); };

If you are using C# 3.0, you can use a lambda expression as well to
make this code even smaller.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Elliot said:
How can I pass the value of variable text to t except declare text at
class level?

..........
string text = "text";
Timer a = new Timer();
a.Interval = 10000;
a.Start();
a.Tick += new EventHandler(t);
..........

private void t(object sender, EventArgs eArgs)
{
}
 

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