Pass parameter to EventHandler

C#Event HandlingParameter Passing

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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);

Solution 2 - C#

If I understand your problem correctly, you are calling a method instead of passing it as a parameter. Try the following:

myTimer.Elapsed += PlayMusicEvent;

where

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

But you need to think about where to store your note.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMattView Question on Stackoverflow
Solution 1 - C#MagnatLUView Answer on Stackoverflow
Solution 2 - C#Dmitry PolyanitsaView Answer on Stackoverflow