Question

I was reading some code and don't understand how base work. Read through some examples but they do not explain my question.

Both give the same output. Why do we need base()?

The code without the base

class B : A
{
    public B()
    {
        Console.WriteLine("B");
    }
}
class A
{
    public A()
    {
        Console.WriteLine("A");
    }
}
class test
{
    static void Main()
    {
        A a = new A();
        B b = new B();
        Console.ReadLine();

    }
}

vs

The code with the base

class B : A
{
    public B():base()
    {
        Console.WriteLine("B");
    }
}
class A
{
    public A()
    {
        Console.WriteLine("A");
    }
}
class test
{
    static void Main()
    {
        A a = new A();
        B b = new B();
        Console.ReadLine();

    }
}
Was it helpful?

Solution

In your example code, it's not necessary because the compiler will implicitly call the default constructor if you don't specify one. However, imagine you had two constructors in the base class:

class A
{
    public A()
    {
        Console.WriteLine("A");
    }

    public A(string foo)
    {
        Console.WriteLine(foo);
    }
}

Now you can specify which base class constructor to call:

class B : A
{
    public B() : base("Foo")
    {
        Console.WriteLine("B");
    }
}

Also, if your base class lacks a default constructor (or if that constructor is inaccessible do to it's protection level), then specifying one in the subclass is required:

class A
{
    public A(string foo)
    {
        Console.WriteLine(foo);
    }
}

class B : A
{
    // Error: 'A' does not contain a constructor that takes 0 arguments
    public B()
    {
        Console.WriteLine("B");
    }
}

OTHER TIPS

In your example it is not important, because by default C# will call a default constructor. This means that the following are essentially the same thing.

class A
{
   public String MyProperty { get; set; }
}

class A 
{
   public A() {}
   public String MyProperty { get; set; }
}

In your call B's constructor is impliticly calling the constructor of it's base class A. If you were to make the A constructor take a parameter:

class A
{
   public A(String myStr) {}
}

then you would find that your code no longer compiles.

base is useful when the constructor on the base object you are calling accepts parameters. It lets you take parameters to the subclasses constructor and pass those up to the base.

class B : A
{
    public B(string msg):base(msg)
    {
        Console.WriteLine("B" + msg);
    }
    public B():base("default message")
    {
        Console.WriteLine("B" + msg);
    }
}
class A
{
    public A(string msg)
    {
        Console.WriteLine("A" + msg);
    }
}

base() is default constructor of super class. it can be usefull if you have multiple constructors defined and what to call specific base constructor.

Base invokes parent ctor, which can set some resources, which are hidden from child classes. In your case you have default constructors and both of them will be invoked, but you can create ctor with parameters in parent class and invoke it from default ctor of child with some arguments. This is widely used in custom Exceptions, for example

in you case it's not necessary. here an example explaining why it's important

 class B : A
    {
        public B(int sharedvalue):base(sharedValue)
        {
            Console.WriteLine("B");
        }
    }
    class A
    {
     private  int _sharedValue;  
        public A(int sharedValue)
        {  // if you have a lot of check to do here it will be best to call the default constructor 
              _sharedValue = sharedValue; 
            Console.WriteLine("A");
        }
      property int SharedProp
    { get{return _sharedValue;} }

    }
    class test
    {
        static void Main()
        { 

            int val = 5 ; 

            A b = new B(val);
            Console.WriteLine(A.SharedProp);

        }
    }

Base is used in constructors. A derived class constructor is required to call the constructor from its base class. When the default constructor isn't present, the custom base constructor can, with base, be referenced.

Example : Program that uses base constructor initializer: C#

using System;

public class A // This is the base class.
{
    public A(int value)
    {
    // Executes some code in the constructor.
    Console.WriteLine("Base constructor A()");
    }
}

public class B : A // This class derives from the previous class.
{
    public B(int value)
    : base(value)
    {
    // The base constructor is called first.
    // ... Then this code is executed.
    Console.WriteLine("Derived constructor B()");
    }
}

class Program
{
    static void Main()
    {
    // Create a new instance of class A, which is the base class.
    // ... Then create an instance of B, which executes the base constructor.
    A a = new A(0);
    B b = new B(1);
    }
}

Output

Base constructor A()

Base constructor A()

Derived constructor B()

Also you can read more : here, here, and here.

It is used to call the parent class constructor! Even though compiler will implicitly call the default constructor of parent class but if you have multiple constructors then you can specify version of constructor you want to call from parent class. Parent class constructor will be called whose signature will match with base().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top