Pass parameter to EventHandler

Matt picture Matt · Dec 27, 2011 · Viewed 158.2k times · Source

I have the following EventHandler to which I added a parameter MusicNote music:

public void PlayMusicEvent(object sender, EventArgs e,MusicNote music)
{
    music.player.Stop();
    System.Timers.Timer myTimer = (System.Timers.Timer)sender;
    myTimer.Stop();
}

I need to add the handler to a Timer like so:

myTimer.Elapsed += new ElapsedEventHandler(PlayMusicEvent(this, e, musicNote));

but get the error:

"Method name expected"

EDIT: In this case I just pass e from the method which contains this code snippet, how would I pass the timer's own EventArgs?

Answer

MagnatLU picture MagnatLU · Dec 27, 2011

Timer.Elapsed expects method of specific signature (with arguments object and EventArgs). If you want to use your PlayMusicEvent method with additional argument evaluated during event registration, you can use lambda expression as an adapter:

myTimer.Elapsed += new ElapsedEventHandler((sender, e) => PlayMusicEvent(sender, e, musicNote));

Edit: you can also use shorter version:

myTimer.Elapsed += (sender, e) => PlayMusicEvent(sender, e, musicNote);