Cataklysim Cataklysim - 1 month ago 8
C# Question

Repeatly subscribing to an event

I came to a point where I created a simple Method that subscribed an event.
I was wondering what will happen if I subsribe it more than one time.

Example:

//This method will be launched everytime a TabSelection Event fires...
public void SampleMethod()
{
this.ctlSample.gridView.SelectionChanged += gridView_SelectionChanged;
}


May there be a Stackoverflow Exception? Like, does he repeadly writes the information onto the memory or is the runtime smart enough to ignore that?

Answer

Your method gridView_SelectionChanged will be executed multiple times when your event is Invoked .

This is one of the things which you can test by yourself and find out really easy.

    public static event EventHandler TestEvent;

    public static void Main(string[] args)
    {
        TestEvent += Program_TestEvent;
        TestEvent += Program_TestEvent;
        TestEvent += Program_TestEvent;

        TestEvent(null, EventArgs.Empty);
     }

    private static void Program_TestEvent(object sender, EventArgs e)
    {
        Console.WriteLine("EVENT");
    }

    //output: 
    //EVENT
    //EVENT
    //EVENT