6

Can someone please explain the meaning of delegate{ } below

public event EventHandler CanExecuteChanged = delegate { };

Also why does it eliminate the need for a null reference check on CanExecuteChanged, and what (if any) are the potential performance hits for using it.

Jeff Anderson
  • 799
  • 7
  • 18
  • 1
    Put simply, it's an empty method (so now `CanExecuteChanged` is bound to a ["NOOP"](https://en.wikipedia.org/wiki/NOP)) – Brad Christie Aug 10 '15 at 18:08

3 Answers3

8

This is a sentinel value for parameterless delegate. It represents an anonymous method that does nothing.

It eliminates the need for null-checking because you can call such delegate without triggering a null reference exception.

Note: This trick becomes less relevant in C# 6.0, because the language provides an alternative syntax to calling delegates that may be null:

delegateThatCouldBeNull?.Invoke(this, value);

Above, null conditional operator ?. combines null checking with a conditional invocation.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

Here delegate { } is an Anonymous method block which will act as an event handler for the hooked up event. You can write necessary event processing logic here. Example below:

public event EventHandler CanExecuteChanged = delegate {
Console.WriteLine("CanExecuteChanged Event has been fired"); };
Rahul
  • 76,197
  • 13
  • 71
  • 125
3

delegate {} is an anonymous method with an empty body. It's a method that does nothing. The CanExecuteChanged event will always have a delegate assigned to it so it will never be null.

The only down side is that you've created a new delegate instance that will live in memory.

shf301
  • 31,086
  • 2
  • 52
  • 86