locked
Are These Two Event Handler Examples Equivalent? RRS feed

  • Question

  • I have found 2 examples of adding an event handler in C#.  The even handler is (obviously) the method named b2_FlashProgressChanged.  Are both of these two forms valid and equivalent?

    BackgroundWorker bw = new BackgroundWorker();
    bw.ProgressChanged += bw_FlashProgressChanged;
    bw.ProgressChanged += new ProgressChangedEventHandler(this.bw_FlashProgressChanged);
    
            private void bw_FlashProgressChanged(object sender, ProgressChangedEventArgs e)
            {
            }
    


    MCSD .NET developer in Dallas, Texas

    Wednesday, March 25, 2015 9:22 PM

Answers

  • Yes. In the initial releases of C# the compiler could not infer the type of a method given just its name so you had to explicitly wrap it in event handler. But a long time back the compiler was updated to allow for type inferencing such that the compiler can verify that a method name matches the signature of a delegate and therefore does not need the explicit conversion anymore. You should prefer the first syntax when possible as it is less typing and easier to read IMO.

    Michael Taylor
    http://blogs.msmvps.com/p3net

    • Marked as answer by DallasSteve Wednesday, March 25, 2015 11:39 PM
    Wednesday, March 25, 2015 9:30 PM

All replies

  • Yes. In the initial releases of C# the compiler could not infer the type of a method given just its name so you had to explicitly wrap it in event handler. But a long time back the compiler was updated to allow for type inferencing such that the compiler can verify that a method name matches the signature of a delegate and therefore does not need the explicit conversion anymore. You should prefer the first syntax when possible as it is less typing and easier to read IMO.

    Michael Taylor
    http://blogs.msmvps.com/p3net

    • Marked as answer by DallasSteve Wednesday, March 25, 2015 11:39 PM
    Wednesday, March 25, 2015 9:30 PM
  • Michael

    Thanks.  That's what I thought.


    MCSD .NET developer in Dallas, Texas

    Wednesday, March 25, 2015 11:43 PM