Cannot determine where the base constructor is called, signing the event

So, here is my code. The output is 2255. But I caanot understand why method in class A will be executed, for we haven't signed the event on it, as we haven't created an instance of class A.

using System;
public delegate void EvHappened();
class A{
    protected int a = 0;
    public event EvHappened AEv;
    public A() {
        this.AEv += EvAHappenedHandler;
    }
    public void EvAHappenedHandler(){
        if (a > 3)
            this.a++;
        Console.Write(a);
    }
    public void methodA() {
        this.AEv();
    }
}

class B : A{
    public event EvHappened BEv;
    public void EvBHappenedHandler() {
        this.a += 2; methodA(); Console.Write(a);
    }
    public void method(){
        this.BEv();
    }
}
class Program{
    static void Main(string[] args){
        B b = new B();
        b.BEv += b.EvBHappenedHandler;
        for (int i = 0; i < 2; i++){
            b.method();
        }
    }
}
Jon Skeet
people
quotationmark

As you haven't declared any constructors in B, the compiler has provided a default constructor - it's as if you'd written:

public class B {
    public B() : base() {
    }

    // Rest of class here
}

So when you call new B(), the A constructor will be executed. That constructor subscribes to the AEv event.

If you had declared a constructor yourself, the behaviour would depend on the constructor initializer:

  • With a constructor initializer of the form this(...), the constructor would chain to another constructor in the same class. Eventually this "chain" will end up with a call to a constructor in the base class.
  • With a constructor initializer of the form base(...), the constructor would chain to the specified constructor in the base class.
  • If you don't specify a constructor initializer at all, it's equivalent to one of the form base().

So whatever you do in the derived class, any constructor always ends up going through a constructor in the base class.

people

See more on this question at Stackoverflow