0

How does an event know which method to call when it is assigned to event handlers with the same name?

Consider the following:

    public static void ImplementExitOnEscape(Window window)
    {
        window.KeyDown += Window_KeyDown;
    }

    private static void Window_KeyDown(object sender, KeyEventArgs e)
    {
        var window = sender as Window;
        // Close window when pressing the escape key.
        if (e.Key == Key.Escape) if (window != null) window.Close();
    }

If I call ImplementExitOnEscape(this) on a window but also:

KeyDown += Window_KeyDown;

        void Window_KeyDown(object sender, KeyEventArgs e)
        {
            MessageBox.Show("Key Down");
        }

then both methods will be executed, even if they have the same name. I already know that you can assign the same event handler multiple times to an event and that the method will be called as many times as it was assigned, but how does it make the difference between two different event handlers with the same name?

IneedHelp
  • 1,630
  • 1
  • 27
  • 58
  • 1
    Names don't matter but also they're not even the same name. You have `ClassA.Window_KeyDown()` and `ClassB.Window_KeyDown()`. The scope allows you to use abbreviations. – H H Sep 22 '12 at 11:54

1 Answers1

4

The method names are human readable and friendly names but they have a different underlying identifier used by the .Net runtime, even if they have the same name in different classes or the same name in the same class but different arguments (i.e. overloaded).

akton
  • 14,148
  • 3
  • 43
  • 47