find and solve || findandsolve.com
Please wait.....

C# Base Keyword

The base keyword is used to access members of the base class or access fields, constructors, and methods from within a derived class.

We use base keywords within an instance method, constructor, or instance property accessor only can't use it inside the static method.

C# base keyword: accessing base class field

You can use the base keyword to access the fields of the base class within the derived class. It is useful if the base and derived classes have the same fields. If the derived class doesn't define the same field, there is no need to use the base keyword. The base class field can be directly accessed by the derived class.

Example

using System;  

public class Color{
    public string ColorName = "Red";
}
public class AnotherColor: Color
{
    string color = "Green";
    public void showColor()
    {
        Console.WriteLine(base.ColorName);
        Console.WriteLine(color);
    }
}
public class BaseClassExample
{
    public static void Main()
    {
        AnotherColor objAnotherColor = new AnotherColor();
        objAnotherColor.showColor();
    }
}  

Output

Red

Green

C# base keyword example: calling base class method

With the help of the base keyword, you can call the base class method also. It is useful if the base and derived classes define the same method. In other words, if the method is overridden. If the derived class doesn't define the same method, there is no need to use the base keyword. The base class method can be directly called by the derived class method.

Example

using System;  

public class Animal{
    public virtual void eat(){
        Console.WriteLine("eating...");
    }
}
public class Cat: Animal
{
    public override void eat()
    {
        base.eat();
        Console.WriteLine("eating bread...");
    }
}
public class BaseClassExample
{
    public static void Main()
    {
        Cat objCat = new Cat();
        objCat.eat();
    }
}  

Output

eating...

eating bread...

C# inheritance: calling base class constructor internally

Whenever we inherit the base class, the base class constructor is internally invoked.

Example

using System;  

public class Animal{
    public Animal(){
        Console.WriteLine("animal...");
    }
}
public class Cat: Animal
{
    public Cat()
    {
        Console.WriteLine("Cat...");
    }
}
public class OverridingExample
{
    public static void Main()
    {
        Cat objCat = new Cat();
    }
}  

Output

animal...

Cat...