Home > Mobile >  Custom EventHandler
Custom EventHandler

Time:01-03

Is it a good practice to pass in a custom non EventArgs class to an EventHandler as such:

public event EventHandler<FooBar> FooBarCreated;

instead of

public event EventHandler<FooBarCreatedEventArgs> FooBarCreated;

public class FooBarCreatedEventArgs : EventArgs 
{
    ...

    public FooBar FooBar { get; }
}

The former is shorter but I seem to see the latter used in Microsoft's docs. Is the latter the proper way?

CodePudding user response:

The Updated .NET Core Event Pattern documentation page states the following:

The previous article discussed the most common event patterns. .NET Core has a more relaxed pattern. In this version, the EventHandler definition no longer has the constraint that TEventArgs must be a class derived from System.EventArgs.

Note, however, that if your class is designed to pass data to the event subscribers, you should still follow the naming convention and add the Args suffix (or EventArgs suffix if you derive from EventArgs).

You can, however, choose not to create a specific class just for event args, if all the data you want to to pass on to the event subscribers is a class you already have.

CodePudding user response:

Yes, the latter is preferred as it makes for more descriptive callback method signatures. E. G.

class FooBarEventObserver
{
   public void OnCreated(object sender, FooBarCreatedEventArgs args)
   {
     ....
   }
  •  Tags:  
  • c#
  • Related