Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching Eventhandler with New Handler vs Directly assigning it

Tags:

syntax

c#

events

What is the actual difference, advantages and disadvantages, of creating a new event handler, vs assigning it directly to the event?

_gMonitor.CollectionChanged += new NotifyCollectionChangedEventHandler(OnCollectionChanged);

vs

_gMonitor.CollectionChanged += OnCollectionChanged;
like image 260
HaxElit Avatar asked Dec 10 '09 22:12

HaxElit


2 Answers

In C# 2.0 and above, they are identical. In C# 1.2 (the one that shipped with .NET 1.1), only the first syntax (with new) compiles ;-p

The second syntax saves key presses, but VS intellisense will typically suggest the first. Ultimately, it makes very little difference. I generally use the second syntax in code-samples online, simply because it avoids going over the (narrow) column width!

like image 147
Marc Gravell Avatar answered Sep 28 '22 06:09

Marc Gravell


The compiler has enough information available to make the new EventHandler effectively syntactic sugar.

It knows that you are attaching an event handler to an event, as only += and -= are valid at this point, so you don't need tell it what to do.

like image 29
ChrisF Avatar answered Sep 28 '22 05:09

ChrisF