Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of delegate{ } [duplicate]

Tags:

c#

delegates

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.

like image 455
Jeff Anderson Avatar asked Aug 10 '15 18:08

Jeff Anderson


People also ask

What is a delegate class?

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.

What is delegate class in C#?

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.

Why use Delegates instead of methods in c#?

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.

What is the role of delegate the net framework?

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.


1 Answers

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.

like image 62
Sergey Kalinichenko Avatar answered Sep 22 '22 02:09

Sergey Kalinichenko