C# Base

In C#, the base keyword is employed to reach base class elements from within the subclass. It is beneficial for triggering the parent class's implementation in cases of override or when necessitating the invocation of the parent constructor in object instantiation. The base class keyword is restricted to usage within an instance method, constructor, or instance property accessor.

Syntax:

It has the following syntax:

Example

base.MemberName   

:base(parameter_list)

In this format,

  • MemberName: This is employed for retrieving the base class member.
  • :base(parameter_list): This is utilized in the derived class constructor to invoke the base class constructor.
  • C# Base keyword to access the base class field

In C# programming, the base keyword is utilized to retrieve the fields of the base class within the derived class. This can be advantageous when both the base and derived classes have identical fields. If the derived class does not explicitly declare the same field, there is no requirement to utilize the base keyword as the base class field can be accessed directly by the derived class.

C# Base keyword example to access the base class field

Let's examine a basic illustration of a base keyword in C#. This keyword enables access to the field of the base class.

Example

Example

using System;  

public class Animal{  

    public string color = "white";  

}  

public class Dog: Animal  

{  

    string color = "black";  

    public void showColor()  

    {  

        Console.WriteLine(base.color);  

        Console.WriteLine(color);  

    }  

      

}  

public class TestBase  

{  

    public static void Main()  

    {  

        Dog d = new Dog();  

        d.showColor();  

    }  

}

Output:

Output

white

black

Explanation:

In this instance, we showcase field hiding by which the Dog class has its own color field that hides the color field from the Animal class. Subsequently, accessing base.color retrieves "white" from Animal, while color retrieves "black" from Dog.

C# base keyword to call the base class method

In C#, we have the ability to invoke the method of the base class by utilizing the base keyword. This feature becomes valuable when both the base class and the derived class have a method with the same name. Essentially, the base keyword is unnecessary if the method is overridden or if the derived class does not have a method with the same name. The derived class method can directly access and call the method from the base class.

C# base keyword example to call the base class method

Let's explore a basic example of a base keyword invoking the method from the base class.

Example

Example

using System;  

public class Animal{  

    public virtual void eat(){  

        Console.WriteLine("eating...");  

    }  

}  

public class Dog: Animal  

{  

    public override void eat()  

    {  

        base.eat();  

        Console.WriteLine("eating bread...");  

    }  

      

}  

public class TestBase  

{  

    public static void Main()  

    {  

        Dog d = new Dog();  

        d.eat();  

    }  

}

Output:

Output

eating...

eating bread...

Explanation:

In this instance, we showcase the utilization of the base keyword to invoke a method from a base class within an overridden method in the subclass. In this scenario, the Dog class overrides the eat function, initially invoking the base Animal method to display "eating...", and then proceeding with its own statement "eating bread…".

C# Base keyword using Constructor Chaining

In C# programming, when one class inherits from another, the constructor of the base class is invoked automatically prior to the constructor of the derived class. The base keyword can also be explicitly employed to invoke a particular constructor of the base class.

C# Base keyword example using constructor chaining

Let's consider a scenario to demonstrate the fundamental keyword by employing constructor chaining in C#.

Example

Example

using System;  

public class Animal{  

    public Animal(){  

        Console.WriteLine("animal...");  

    }  

}  

public class Dog: Animal  

{  

    public Dog()  

    {  

        Console.WriteLine("dog...");  

    }  

      

}  

public class TestOverriding  

{  

    public static void Main()  

    {  

        Dog d = new Dog();            

    }  

}

Output:

Output

animal...

dog...

Explanation:

In this instance, we showcase constructor chaining within inheritance. When creating a Dog instance, it first triggers the Animal constructor, displaying "animal...", and then proceeds to the Dog constructor, displaying "dog...".

Constructors Chaining with Parameters in C#

When a base class in C# specifies a constructor with parameters, it is essential to invoke the constructor of the derived class explicitly to guarantee appropriate initialization. This is achieved by invoking the parameterized constructor of the base class inside the constructor of the derived class using the base keyword along with the necessary parameters. This practice guarantees that the base class is correctly initialized with the specified parameters prior to the execution of the derived class constructor.

C# Constructors Chaining with Parameters Example

Let's consider an example to demonstrate constructor chaining with arguments in C#.

Example

Example

using System;

public class Animal

{

    public Animal(string name)

    {

        Console.WriteLine($"Animal constructor: {name}");

    }

}

public class Dog : Animal

{

    public Dog(string name) : base(name)  

    {

        Console.WriteLine("Dog constructor");

    }

}

public class Program

{

    public static void Main()

    {

        Dog d = new Dog("Buddy");

    }

}

Output:

Output

Animal constructor: Buddy

Dog constructor

Explanation:

In this illustration, we showcase constructor chaining with parameters. When initializing a Dog object with the name "Buddy," it triggers an initial invocation of the Animal class constructor using base(name) to display "Animal constructor: Buddy". Subsequently, the Dog constructor is executed, resulting in the output "Dog constructor".

Difference Between base and this keyword in C#

There exist various distinctions between the base and this keywords in C#. Some key variances are outlined below:

This keyword

  • The term "this" refers to the current instance of the class where the code is being executed.
  • It allows access to members (fields, properties, and methods) of the immediate class, including any overridden or hidden members from a base class.
  • When a method is called using this.Method, it invokes the most derived override of that method.
  • Base Keyword

  • The base keyword is a reference to the immediate base class of the current class.
  • It refers to members as declared in the base class, overriding any overrides or hiding in the immediate class.
  • When calling a method with base.Method, it invokes the parent class version even if it is overridden in the derived class.
  • C# Example using base and this keyword

Let's consider a scenario to demonstrate the base and this keywords in C#.

Example

Example

using System;

public class Shape

{

    public virtual double Area()

    {

        Console.WriteLine("Shape Area: 0");

        return 0;

    }



    public void PrintType()

    {

        Console.WriteLine("This is a Shape");

    }

}

public class Rectangle : Shape

{

    private double width;

    private double height;

    public Rectangle(double w, double h)

    {

        width = w;

        height = h;

    }

    public override double Area()

    {

        base.Area(); 

        double rectArea = width * height;

        Console.WriteLine($"Rectangle Area (overridden): {rectArea}");

        return rectArea;

    }

    public new void PrintType()

    {

        Console.WriteLine("This is a Rectangle");

    }

    public void ShowInfo()

    {

        Area();            

        base.Area();      

        base.PrintType();  

        this.PrintType();  

    }

}

class Program

{

    static void Main()

    {

        Rectangle rect = new Rectangle(5, 4);

        rect.ShowInfo();

    }

}

Output:

Output

Shape Area: 0

Rectangle Area (overridden): 20

Shape Area: 0

This is a Shape

This is a Rectangle

Explanation:

In this instance, we are examining a Rectangle class that extends Shape and redefines the Area method while concealing the PrintType method with new. Within the ShowInfo function, both base and this references are employed to showcase the distinct accessibility of base class methods (base.Area, base.PrintType) and derived class methods (this.PrintType, Area override).

Conclusion

In summary, the fundamental keyword is a necessary component of object-oriented programming in C# that allows a subclass to communicate with its direct superclass. The "base" keyword is employed to call superclass constructors, utilize superclass members and properties, and resolve issues related to subclass members potentially overshadowing superclass members. Proper utilization of this keyword results in more organized inheritance structures, code reusability, and minimized ambiguity when accessing members within intricate class hierarchies.

C# Base FAQs

In a derived class, it is possible to utilize multiple constructors. When doing so, the derived class can select a specific base class constructor to call by using the initializer list in the derived class constructor. This allows for flexibility in choosing the appropriate base class constructor based on the requirements of the derived class.

Yes, it is possible to have multiple constructors in a subclass. Each constructor in the subclass can invoke a specific constructor from the base class by using the base keyword along with the necessary arguments.

What occurs if the base class does not have a public parameterless constructor?

The subclass must explicitly invoke a constructor from the superclass using the base keyword and choose from the existing parameter variations. Failure to do so will result in a compilation error.

The base keyword should be utilized in methods when there is a need to access a method from a parent class within a derived class.

Utilize the base keyword when needing to reference a method or property of the base class that has been overridden or concealed by the derived class.

4) Does C# allow multiple base class inheritance?

No, in C#, it is not possible to have multiple class inheritance. In C#, a class can inherit from only one base class, however, it can implement multiple interfaces.

5) Is it possible to apply a base to fields and properties within a class?

Yes, a base class can access fields, properties, and methods of the base class that are available in the derived class. This is commonly used when the derived class overrides a member of the base class.

Input Required

This code uses input(). Please provide values below: