Search code examples
c#interopfxcop

Remove all, except the first two parameters from the EventHandler


I am having trouble with the warning CA1009 from FxCop to remove all the poarameters except the first two from the event (object and EventArgs). I have not found the way to solve this issue, bécause none of those parameters should be of type object or EventArgs. I tried to create two classes of both types and include the parameters as properties, but it did not use the parameters / properties.

Doc.cs

public delegate void UpdateZedGraphCounterDelegate(double[] newPackedOp, int i, double[] previousPackedOp, string numberLabel);
public static event UpdateZedGraphCounterDelegate LUTSelectionChanged;
private static void OnLUTSelectionChanged(double[] newPackedOp, int i, double[] previousPackedOp, string numberLabel)
{
    LUTSelectionChanged?.Invoke(newPackedOp, i, previousPackedOp, numberLabel);
}

Solution

  • You should wrap all the arguments in a single class that derives from EventArgs:

    public sealed class LUTSelectionChangedEventArgs: EventArgs
    {
        public LUTSelectionChangedEventArgs(double[] newPackedOp, int i, double[] previousPackedOp, string numberLabel)
        {
            NewPackedOp      = newPackedOp;
            I                = i;
            PreviousPackedOp = previousPackedOp;
            NumberLabel      = numberLabel;
        }
    
        public double[] NewPackedOp      { get; }
        public int      I                { get; }
        public double[] PreviousPackedOp { get; }
        public string   NumberLabel      { get; }
    }
    

    Then declare your event like so:

    public static event EventHandler<LUTSelectionChangedEventArgs> LUTSelectionChanged;
    

    And call it thusly:

    private static void OnLUTSelectionChanged(double[] newPackedOp, int i, double[] previousPackedOp, string numberLabel)
    {
        LUTSelectionChanged?.Invoke(sender: null, new LUTSelectionChangedEventArgs(newPackedOp, i, previousPackedOp, numberLabel));
    }
    

    Note how you have to pass sender as null because it's being called from a static method that has no this reference.

    It's not usual to have a null sender like that, so beware. Normally, an event is raised from an object, and a reference to the object is passed as the sender parameter. You should consider making it all non-static, or pass in the sender object to your OnLUTSelectionChanged() method so that you can pass it as the sender parameter of .Invoke().