What does this weird C # lambda operator do?

Looking at some source code, I found this operator

() => { } 

From reading MSDN, now I know that this is a lambda operator, but what effect will it have on () through {}? It is used as an argument to the class constructor.

+4
source share
5 answers

This is an Action (void, no parameters) delegate with a body that does nothing. Useful when a non-zero delegate is needed (perhaps to simplify a callback or call an event, since calling null is an error), but you have nothing specific.

+13
source

He can be called an empty delegate. It does nothing, but it's safe to call it without checking for null s. Type of placeholder.

I use it as follows:

  event Action SafeEvent = () => { }; event Action NullableEvent; void Meth() { //Always ok SafeEvent(); //Not safe NullableEvent(); //Safe if (NullableEvent != null) NullableEvent(); } 
+7
source

This is for the Action parameter in the constructor, probably. By doing () => { } , which gives the object a valid action to execute that does nothing when called.

+3
source
Parameter List

()

=> lambda call

{} scope of the executable code (optional if it is single-line)

+3
source

This can help you understand more clearly ...

() => {}

equivalently

function () {}

another example:

(i) => {i + = 1; }

equivalently

function (int i) {i + = 1; }

+2
source

Source: https://habr.com/ru/post/1347950/


All Articles