Remove all, except the first two parameters from the EventHandler

158 Views Asked by At

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

There are 2 best solutions below

0
Matthew Watson On BEST ANSWER

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().

0
sommmen On

Just a small addition to the answer of @matthew,

See the guidelines on events:

https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/event

✔️ DO use System.EventHandler instead of manually creating new delegates to be used as event handlers.

This is most likely why this style rule was there in place. So refactor your custom event handler to use a custom object, instead of several parameters.