Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this weird lambda C# operator do?

Tags:

c#

lambda

Looking at some source code, I found this operator

() => { }

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

like image 482
Tanner Avatar asked Nov 27 '22 14:11

Tanner


2 Answers

It is an Action (void, no parameters) delegate with a body that does nothing. Useful for when a non-null delegate is needed (perhaps to simplify callback or event invocation, as invoking on a null is an error), but you have nothing specific to do.

like image 53
Marc Gravell Avatar answered Dec 09 '22 08:12

Marc Gravell


It can be called empty delegate. It does nothing, but it is safe to call it without checking for nulls. Sort of placeholder.

I use it like this:

    event Action SafeEvent = () => { };

    event Action NullableEvent;        

    void Meth()
    {
        //Always ok
        SafeEvent();

        //Not safe
        NullableEvent();

        //Safe
        if (NullableEvent != null)
            NullableEvent();
    }
like image 22
Andrey Avatar answered Dec 09 '22 08:12

Andrey