For example, is there anything wrong with something like this?
private void button1_Click(object sender, EventArgs e)
{
Packet packet = new Packet();
packet.DataNotSent += packet_DataNotSent;
packet.Send();
}
private void packet_DataNotSent(object sender, EventArgs e)
{
Console.WriteLine("Packet wasn't sent.");
}
class Packet
{
public event EventHandler DataNotSent;
public void Send()
{
if (DataNotSent != null)
{
DataNotSent(null, EventArgs.Empty);
}
}
}
If it were just a simple integer variable declaration it would be fine because once it went out of scope and would later be collected by the garbage collector but events are a bit .. longer-living? Do I have to manually unsubscribe or take any sort of measures to make sure this works properly?
It just feels.. weird. Not sure if it is correct or not. Usually when I add to an event handler it lasts for the entirety of the application so I'm not sure about what happens when constantly adding and removing event handlers.