[ACCEPTED]-In C#, do you need to call the base constructor?-constructor
You do not need to explicitly call the base 4 constructor, it will be implicitly called.
Extend 3 your example a little and create a Console 2 Application and you can verify this behaviour 1 for yourself:
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
MyClass foo = new MyClass();
Console.ReadLine();
}
}
class BaseClass
{
public BaseClass()
{
Console.WriteLine("BaseClass constructor called.");
}
}
class MyClass : BaseClass
{
public MyClass()
{
Console.WriteLine("MyClass constructor called.");
}
}
}
It is implied, provided it is parameterless. This 2 is because you need to implement constructors that take values, see the code below for 1 an example:
public class SuperClassEmptyCtor
{
public SuperClassEmptyCtor()
{
// Default Ctor
}
}
public class SubClassA : SuperClassEmptyCtor
{
// No Ctor's this is fine since we have
// a default (empty ctor in the base)
}
public class SuperClassCtor
{
public SuperClassCtor(string value)
{
// Default Ctor
}
}
public class SubClassB : SuperClassCtor
{
// This fails because we need to satisfy
// the ctor for the base class.
}
public class SubClassC : SuperClassCtor
{
public SubClassC(string value) : base(value)
{
// make it easy and pipe the params
// straight to the base!
}
}
It's implied for base parameterless constructors, but 2 it is needed for defaults in the current 1 class:
public class BaseClass {
protected string X;
public BaseClass() {
this.X = "Foo";
}
}
public class MyClass : BaseClass
{
public MyClass()
// no ref to base needed
{
// initialise stuff
this.X = "bar";
}
public MyClass(int param1, string param2)
:this() // This is needed to hit the parameterless ..ctor
{
// this.X will be "bar"
}
public MyClass(string param1, int param2)
// :base() // can be implied
{
// this.X will be "foo"
}
}
It is implied.
0
A derived class is built upon the base class. If 6 you think about it, the base object has 5 to be instantiated in memory before the 4 derived class can be appended to it. So 3 the base object will be created on the way 2 to creating the derived object. So no, you 1 do not call the constructor.
AFAIK, you only need to call the base constructor 1 if you need to pass down any values to it.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.