Does anyone know what is the behavior for C#? Is it the same for all .NET languages?
views:
530answers:
5Yes, it automatically calls the default constructor of the base class. A default constructor has no parameters.
If there is not a default constructor, you must manually call the base class constructor using the syntax:
public MyClass() : base(parameters, ...)
Source: Using Constructors (C#)
Yes it does. This is why you cannot create a derived class that doesn't call a base class.
public class A
{
public A(string s)
{}
}
public class B : A
{
public B()
{}
}
Results in a compiler error.
It definitely does for C# - I cannot say for other languages but I cannot imagine that their compilers would generate different IL.
Take this example:
class Parent { }
class Child : Parent { }
If we look at the IL generated inside the Child
's constructor we see this important line:
L_0001: call instance void Parent::.ctor()
which clearly shows that we are calling the default constructor of the Parent
class.
Yes - this happens with any constructor in the derived class if you don't explicitly call a base class constructor.
class Base
{
Base(){}
Base(int i){}
}
class Derived : Base
{
Derived(bool x) {} // calls Base.Base()
}
class Derived2 : Base
{
Derived2() : base(10) {} // calls Base.Base(int)
}
Just to add to the other answers, for OO to work correctly, it MUST call a constructor for each class. If not, you couldn't guarantee that your class was in a known good condition.
Even when you are doing something strange (such as serializing) they require that a default constructor because, again, a constructor MUST be called.