Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What constitutes 'redundant delegate creation'?

Tags:

c#

.net

delegates

I was registering to an event in my class, and as per usual I was lazy and just use the autocomplete feature built into Visual Studio 2008 Pro which auto creates the delegate creation and it's associated method.

public abstract class FooBase
{
    protected event EventHandler<MyValueChangedArgs> MyValueChanged;

    protected FooBase()
    {
        MyValueChanged +=
            new EventHandler<MyValueChangedArgs>(HandleMyValueChanged);
    }

    private void HandleMyValueChanged(object sender, MyValueChangedArgs e)
    {
        // Some handling logic
    }
}

Usually I dont think twice when Visual Studio gens the event handler for me, but then I received a recommendation from Refactor! Pro to "Remove Redundant Delegate Creation". The recommendation results in:

public abstract class FooBase
{
    protected event EventHandler<MyValueChangedArgs> MyValueChanged;

    protected FooBase()
    {
        MyValueChanged += HandleMyValueChanged;
    }

    private void HandleMyValueChanged(object sender, MyValueChangedArgs e)
    {
        // Some handling logic
    }
}

Under what circumstances is delegate creation redundant and when is delegate creation appropriate?

Thanks.

like image 446
Llyle Avatar asked Jan 31 '09 05:01

Llyle


2 Answers

I think that Refactor! tells you that the line

MyValueChanged += new EventHandler<MyValueChangedArgs>(HandleMyValueChanged);

Can be shortened and the compiler will infer a event handler creation and the TEventArgs type argument...

Under what circumstances is delegate creation redundant and when is delegate creation appropriate?

On designer-generated code...

like image 54
Christian C. Salvadó Avatar answered Oct 15 '22 11:10

Christian C. Salvadó


Sorry about that. We just didn't have time in the product schedule to generate the shorter code when anonymous methods were added to C#.

I always edit the generated code to remove the extra syntax.

like image 37
Jay Bazuzi Avatar answered Oct 15 '22 09:10

Jay Bazuzi