Abstract events implemented, but compiler warns they aren't used
I have an abstract class that declares abstract events that derived classes are required to implement. That allows owners of the class who have only a reference to the base type to subscribe to those events. But not all of the derived classes fire those events. Now the compiler is complaining those events aren't being used. Any suggestions on what I can do about those warnings?
9 Replies
"not being used" means you have nobody using it. which might be perfectly valid.
It's like the compiler is suggesting I can remove the event, but then my base class isn't completely implemented.
Why override it?
It's abstract.
And not just make it virtual?
Only the derived class can ever fire it. If it's virtual, then only the base class has that option.
That's why the pattern is to make On* methods.
https://learn.microsoft.com/en-us/dotnet/standard/events/
Typically, to raise an event, you add a method that is marked as protected and virtual (in C#) or Protected and Overridable (in Visual Basic). Name this method OnEventName; for example, OnDataReceived. The method should take one parameter that specifies an event data object, which is an object of type EventArgs or a derived type. You provide this method to enable derived classes to override the logic for raising the event. A derived class should always call the OnEventName method of the base class to ensure that registered delegates receive the event.
Handling and Raising Events - .NET
Learn to handle and raise .NET events, which are based on the delegate model. This model lets subscribers register with or receive notifications from providers.
I ended up providing
protected
Fire* methods. On* is taken by event handlers. This is a sender, not a handler.
The On* methods you mentioned do fire the event, but they let the derived class handle the event too. Those are virtual.