When is it better to use the explicit use of the delegate keyword instead of lambda?

Is there any best practice regarding coding style regarding explicit use of a keyword delegateinstead of using lambda?

eg.

new Thread(() =>
{
    // work item 1
    // work item 2
}).Start();

new Thread(delegate()
{
    // work item 1
    // work item 2
}).Start();

I think lambda looks better. If lambda is better, then what is the point of having a keyword delegateother than the fact that it existed before lambda was implemented?

+3
source share
1 answer

Lambda , , ( , , , ).

delegate , :

object.Event += delegate { };

, :

object.Event += (sender,args) => { };

/ .

EDIT: (, , ), , hander for Null Object: -

class MyClassThatFiresWithoutTheTrick
{
    public event EventHandler MyEvent; // implicit = null

    // Need a method to keep this DRY as each fire requires a null check - see Framework Design Guidelines by Abrams and Cwalina
    protected virtual void OnMyEvent()
    {
        // need to take a copy to avoid race conditions with _removes
        // See CLR via C# 3rd edition p 264-5 for reason why this happens to work
        //var handler = MyEvent;
        // BUT THIS is the preferred version
        var handler = Interlocked.CompareExchange( ref MyEvent, null, null);
        // Need to do this check as it might not have been overridden
        if( handler == null)
            return;
        handler( this, EventArgs.Empty );
    }
}

class MyClassThatFiresWithTheTrick
{
    public event EventHandler MyEvent = delegate{};

    protected virtual void OnMyEvent()
    {
        MyEvent( this, EventArgs.Empty );
    }
}

( , , OnMyEvent, .)

+4

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


All Articles