Search code examples
c#eventsclass

.NET Event Best Practice - Expose via property or return in EventArgs


I'm unsure about the best practice for event handling/class design.

I have a class that has a method Discover(). When the method completes it raises an event, DiscoveryCompleted. The DiscoveryCompleted event has EventArgs.

In the Discover() method a List of objects are created. Should these be returned when the DiscoveryCompleted event fires in the EventArgs (will still need to create a class that derives from EventArgs), or be set as a property (ReadOnlyCollection) on the class. I have a bool Discovered which is set when the DiscoveryCompleted fires, so this can be used to determine if data should be populated.


Solution

  • I think this ultimately boils down to the architecture / extensibility points you want to enable with your code. Does a consumer of the Discover function always want to / need to interact with the objects that are discovered? If so then they should be returned from the Discover method. However, if calling Discover keeps those objects for use internally with other methods, and knowing which objects were discovered were optional (or you don't want to do something with them beyond the classes core functionality every time), then providing the information through an event is a good choice.