Reputation: 19
I'm wanting to pass some parameters to the event timer_tick in c# but I don't want to make them global variables. Is this possible?
I had a look round and came up with something like this:
//Where I start the timer
lift1Up.Enabled = true;
lift1Up.Tick += (sender, args) => lift1Up_Tick(sender, args, destination, currentFloor);
lift1Up.Start();
private void lift1Up_Tick(object sender, EventArgs e, int dest, int current)
{
//my code
}
Many thanks! Luke.
Upvotes: 1
Views: 4314
Reputation: 61686
You can just use a lambda for your event handler, and access your local variables from there, the C# compiler will do the magic:
void StartTimer()
{
EventHandler tickHandler = null;
var destination = 5, currentFloor = 0;
tickHandler = (sender, args) =>
{
if (currentFloor == destination)
{
lift1Up.Enabled = false;
lift1Up.Tick -= tickHandler;
MessageBox.Show("Arrived!");
}
else
currentFloor++;
}
// start the timer
lift1Up.Tick += tickHandler;
lift1Up.Enabled = true;
}
Upvotes: 2
Reputation: 266
Yes, you can use Lambda functions, as used in the example mentioned. Lambda functions are a form of nested function, in that they allow access to variables in the scope of the containing function. Lambda expression is defined as:
(input parameters) => expression;
(input parameters) => {statement block};
So, you can execute any expression or statement block, like call method, with the visibility of all variables of the scope, including event variables, without need to make them global variables.
Upvotes: 0
Reputation: 101701
Yes,but not like that. You can define a class by inheriting from EventArgs
class MyEventArgs : EventArgs
{
public int dest { get; set; }
public int current { get; set; }
}
Then you need to manually trigger Tick
event and pass parameters like this:
lift1Up_Tick(this, new MyEventArgs { dest = 23, current = 100 });
And in tick event you can get this arguments:
private void lift1Up_Tick(object sender, EventArgs e)
{
var args = (MyEventArgs)e;
int dest = args.dest;
}
I don't know is there a better way.To do this (manuel trigger) you can add another timer.Set it's interval then write this code inside of it's Tick event:
lift1Up_Tick(this, new MyEventArgs { dest = 23, current = 100 });
Upvotes: 1