user310291
user310291

Reputation: 38228

When would I need to call base() in C#?

My BaseClass Constructor is called whereas I have a constructor in derived class so when would I need to call base() ?

class BaseClass
{
    public BaseClass()
    {
        Debug.Print("BaseClass");
    }
}

class InheritedClass : BaseClass
{
    public InheritedClass()
    {
        Debug.Print("InheritedClass");
    }
}

private void Form1_Load(object sender, EventArgs e)
{
    InheritedClass inheritedClass = new InheritedClass();
}

Output

'Inheritance.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\Accessibility\v4.0_4.0.0.0__b03f5f7f11d50a3a\Accessibility.dll'
'Inheritance.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
BaseClass
InheritedClass
The thread 'vshost.RunParkingWindow' (0x12b4) has exited with code 0 (0x0).
The thread '<No Name>' (0x85c) has exited with code 0 (0x0).
The program '[4368] Inheritance.vshost.exe: Program Trace' has exited with code 0 (0x0).
The program '[4368] Inheritance.vshost.exe: Managed (v4.0.30319)' has exited with code 0 (0x0).

Upvotes: 3

Views: 114

Answers (2)

Amir Popovich
Amir Popovich

Reputation: 29846

When you have a non-default base constructor(e.g. with param overloads).

Example:

public class BaseClass
{
  public BaseClass(int number)
  {
     // DoSomething
  }

  public BaseClass(string str)
  {
    // Do Something
  }
}

public class DerivedClass : BaseClass
{
   public DerivedClass(): base(7){} 
   public DerivedClass(string str) : base(str){}
}

Upvotes: 9

MPelletier
MPelletier

Reputation: 16709

The default base() constructor itself is called automatically.

public class DerivedClass : BaseClass
{
   public DerivedClass(): base() // No harm done, but this is redundant
   {}
   //same as
   public DerivedClass()
   {}
}

The only time it is not called automatically is when something else, like a parametered base constructor is called. Exactly as in Amir Popovich's excellent answer.

Upvotes: 0

Related Questions