SonarSource / sonar-dotnet

Code analyzer for C# and VB.NET projects
https://redirect.sonarsource.com/plugins/csharp.html
GNU Lesser General Public License v3.0
797 stars 229 forks source link

Fix S3257 FP: Following the suggestion to remove the explicit delegate creation, leads to runtime crash #9694

Open lsw-sma opened 1 week ago

lsw-sma commented 1 week ago

Description

Rule ID: S3257 UserControl provides the method AddHandler(RoutedEvent routedEvent, Delegate handler). If I pass new RoutedEventHandler(OnErrorEvent) as the handler argument the rule is raised. If I follow the suggestion and pass OnErrorEventdirectly, it leads to the runtime exception: System.ArgumentException: 'Handler type is mismatched.'

Repro steps

  1. Create a System.Windows.Controls.UserControl (named UserControl1)
  2. Change the codebehind to the following:

    public partial class UserControl1 {
    public UserControl1() {
        InitializeComponent();
    
        // Raises rule, no problem at runtime
        AddHandler(System.Windows.Controls.Validation.ErrorEvent, new RoutedEventHandler(OnErrorEvent));
    
        // Valid according to rule, but leads to runtime exception
        AddHandler(System.Windows.Controls.Validation.ErrorEvent, OnErrorEvent);
    }
    
    private void OnErrorEvent(object sender, RoutedEventArgs e) { }
    }

Expected behavior

S3257 should not raise for passing new RoutedEventHandler(OnErrorEvent) to AddHandler.

Actual behavior

S3257 falsely suggests to pass the argument as a method group. This leads to a runtime exception: System.ArgumentException: 'Handler type is mismatched.'

Known workarounds

  1. Disable the rule locally.
  2. Extracting the argument as a variable, i.e.
    var eventHandler = new RoutedEventHandler(OnErrorEvent);
    AddHandler(System.Windows.Controls.Validation.ErrorEvent, eventHandler);

    Related information