Search code examples
c#eventsevent-handlingmethod-group

+= Operator and the new Operator c#


Whats the differenct when using the += operator followed by a "new function" vs only the function name?

Eg

FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Created += new FileSystemEventHandler(OnChanged);

or

FileSystemWatcher _fileSystemWatcher = new FileSystemWatcher(pathName);
_fileSystemWatcher.Created += _fileSystemWatcher_Created;

The later works, is there some rules about when to using what?


Solution

  • When dealing with events doing

    watcher.Created += new FileSystemEventHandler(OnChanged);
    

    and

    watcher.Created += OnChanged;
    

    mean the exact same thing. Before C# 2.0 you could only do the first syntax, the shorter syntax was added later.