8

On a build server, I see some weird message. It doesn't say so, but I think it's from some software called 'fx cop'

Warning CS0067: The event 'SunGard.Adaptiv.AnalyticsEngine.UI.CommonControls.DisabledCommand.CanExecuteChanged' is never used

How can I silence this message? Without changing what my class does.

sealed class DisabledCommand : ICommand
{
    public event EventHandler CanExecuteChanged;

I stumbled upon docs for System.Diagnostics.CodeAnalysis.SuppressMessageAttribute which sounds useful, but there aren't any examples for my warning.

nalka
  • 1,894
  • 11
  • 26
Colonel Panic
  • 132,665
  • 89
  • 401
  • 465

1 Answers1

19

If you need to create an event that is never raised, you should make a noop event:

public EventHandler CanExecuteChanged {
    add { }
    remove { }
}

The compiler is complaining because a default ("field-like") event will create a hidden backing field to store the handlers. Since you never raise the event, that field just wastes memory.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 3
    I would consider to implement the event using *explicit interface implementation*, so the event is hidden when the actual implementation type is used directly. – Ramon de Klein Nov 10 '17 at 18:32
  • @RamondeKlein I tried that, but it didn't make the warning go away. – RobSiklos Dec 14 '18 at 20:09
  • Also consider putting `throw NotSupportedException();` inside both the `add` accessor and the `remove` accessor. Plus @RamondeKlein's suggestion. So a full solution could be `EventHandler ICommand.CanExecuteChanged { add { throw NotSupportedException(); } remove { throw NotSupportedException(); } }` – Jeppe Stig Nielsen Jan 12 '23 at 17:00