tags:

views:

530

answers:

5

Does anyone know what is the behavior for C#? Is it the same for all .NET languages?

+5  A: 

Yes, 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#)

NilObject
+1  A: 

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.

Quibblesome
If you have a default constructor (no parameters) on the base class, there will be no compiler error.
NilObject
Indeed but this proves you cannot create a derived class without calling a base class ctor. If it was permissable this would work.
Quibblesome
+1  A: 

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.

Andrew Hare
+2  A: 

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)
}
orip
Is this the default behavior for all .NET languages?
Igor Zelaya
It's probably the default behavior for all object-oriented languages. Intuitively, the base class's members must be set up before the derived class's members or you'd get unpredictable results.
rmeador
A: 

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.

Bill K