>
>
>
V3119. Calling a virtual (overridden) e…


V3119. Calling a virtual (overridden) event may lead to unpredictable behavior. Consider implementing event accessors explicitly or use 'sealed' keyword.

The analyzer detected usage of a virtual or overridden event. If this event is overridden in a derived class, it may lead to unpredictable behavior. MSDN does not recommend using overridden virtual events: "Do not declare virtual events in a base class and override them in a derived class. The C# compiler does not handle these correctly and it is unpredictable whether a subscriber to the derived event will actually be subscribing to the base class event". https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/events/how-to-raise-base-class-events-in-derived-classes.

Consider the following example:

class Base
{
  public virtual event Action MyEvent;
  public void FooBase() { MyEvent?.Invoke(); }
}
class Child: Base
{
  public override event Action MyEvent;
  public void FooChild() { MyEvent?.Invoke(); }
}
static void Main()
{
  var child = new Child();
  child.MyEvent += () => Console.WriteLine("Handler");
  child.FooChild();
  child.FooBase();
}

Even though both methods 'FooChild()' and 'FooBase()' are called, the 'Main()' method will print only one line:

Handler

If we used a debugger or test output, we could see that the 'MyEvent' variable's value was 'null' when calling to 'child.FooBase()'. It means that the subscriber to the 'MyEvent' event in the 'Child' class, which is derived from 'Base' and overrides this event, did not subscribe to the 'MyEvent' event in the base class. This behavior seems to contradict the behavior of virtual methods, for example, but it can be explained by the specifics of event implementation in C#. When declaring an event, the compiler automatically creates two accessor methods to handle it, 'add' and 'remove', and also a delegate field where delegates are added to\removed from when subscribing to\unsubscribing from events. For a virtual event, the base and derived classes will have individual (not virtual) fields associated with this event.

This issue can be avoided by declaring event accessors explicitly:

class Base
{
  public virtual Action _myEvent { get; set; }
  public virtual event Action MyEvent
  {
    add
    {
      _myEvent += value;
    }
    remove
    {
      _myEvent -= value;
    }
  }
  public void FooBase() { _myEvent?.Invoke(); }
}

We strongly recommend that you do not use virtual or overridden events in the way shown by the first example. If you still have to use overridden events (for example, when deriving from an abstract class), use them carefully, allowing for the possible undefined behavior. Declare accessors 'add' and 'remove' explicitly, or use the 'sealed' keyword when declaring a class or event.

You can look at examples of errors detected by the V3119 diagnostic.