开发者

When is it better practice to explicitly use the delegate keyword instead of a lambda?

开发者 https://www.devze.com 2022-12-13 04:52 出处:网络
Is there any best practice with respect to coding style with开发者_开发百科 respect to explicit use of the delegate keyword instead of using a lambda?

Is there any best practice with respect to coding style with开发者_开发百科 respect to explicit use of the delegate keyword instead of using a lambda?

e.g.

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

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

I think the lambda looks better. If the lambda is better style, what's the point of having a delegate keyword, other than for the fact that it existed before lambdas were implemented?


Lambda syntax is much more generalised, and the designers have said that they'd ideally remove the old overlapping syntaxes (dont have a citation, but it's probably Eric Lippert or Jon Skeet in a book or a podcast).

But delegate allows you to ignore parameters, e.g.:

object.Event += delegate { };

versus having to say:

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

which can be very useful in large argument lists and/or to make the code more resilient to refactoring.

EDIT: As pointed out by Yann Schwartz in another answer (now unfortunately deleted), a very neat usage of this trick is in order to provide a default hander for an event using the Null Object pattern:-

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 );
    }
}

(though what you might often end up doing is an Inline Method of OnMyEvent, making the code even shorter again.)

0

精彩评论

暂无评论...
验证码 换一张
取 消