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.
Delegates are the library class in System namespace. These are the type-safe pointer of any method. Delegates are mainly used in implementing the call-back methods and events. Delegates can be chained together as two or more methods can be called on a single event.
A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.
Delegates in C# are similar to function pointers in C++, but C# delegates are type safe. You can pass methods as parameters to a delegate to allow the delegate to point to the method. Delegates are used to define callback methods and implement event handling, and they are declared using the “delegate” keyword.
In the . NET environment, a delegate is a type that defines a method signature and it can pass a function as a parameter. In simple words we can say delegate is a . NET object which points to a method that matches its specific signature.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With