title: How virtual events work in C#?
body: <p>Below is the program I used for the test.
  It prints (as expected):</p>
  
  <pre><code>Raise A
  Event from A
  Raise B
  Event from B
  </code></pre>
  
  <p>Now, if we change first two lines of the Main to be:</p>
  
  <pre><code>        A a = new B();
          B b = new B();
  </code></pre>
  
  <p>the Program will print:</p>
  
  <pre><code>Raise A
  Raise B
  Event from B
  </code></pre>
  
  <p>which is also expected, as overriding event hides the private backing field in the base class and therefore events fired by the base class are not visible to clients of the derived class.</p>
  
  <p>Now I am changing the same lines to:</p>
  
  <pre><code> B b = new B();
   A a = b;
  </code></pre>
  
  <p>and the program starts printing:</p>
  
  <pre><code>Raise A
  Raise B
  Event from A
  Event from B
  </code></pre>
  
  <p>What's going on?</p>
  
  <pre><code>class A
  {
      public virtual event EventHandler VirtualEvent;
      public void RaiseA()
      {
          Console.WriteLine("Raise A");
          if (VirtualEvent != null)
          {
              VirtualEvent(this, EventArgs.Empty);
          }
      }
  }
  class B : A
  {
      public override event EventHandler VirtualEvent;
      public void RaiseB()
      {
          Console.WriteLine("Raise B");             
          if (VirtualEvent != null)
          {
              VirtualEvent(this, EventArgs.Empty);
          }
      }
  }
  
  class Program
  {
      static void Main(string[] args)
      {
          A a = new A();
          B b = new B();
  
          a.VirtualEvent += (s, e) =&gt; Console.WriteLine("Event from A");
          b.VirtualEvent += (s, e) =&gt; Console.WriteLine("Event from B");
  
          a.RaiseA();
          b.RaiseB();
      }
  }
  </code></pre>