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.
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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With