Member-only story

base keyword in c#

Shahzad Aslam
2 min readMay 5, 2024

--

When you have inheritance between two or more classes. One is base classs (parent class). Another is derived class (child class). You want to access the members such as fields, properties, and methods, within a derived class. In this type of situation you can use base keyword in derived class to access members of base class.

base keyword in c#

Accessing Base Class Constructor:

When you want to explicitly call a constructor of the base class from within a constructor of the derived class. You can write the code with base keyword before the call of the constructor of the derived call. It will execute the base classs constructor before the execution of the derived class constructor.

Example

// Base class (parent class)
public class Fruit
{
// Base class constructor.
public Fruit(string name)
{
Console.WriteLine("Fruit name is : {0}", name);
}
}

// Derive class (child class)
public class Apple: Fruit
{
// Derived class constructor.
public Apple(string name): base(name)
{
Console.WriteLine("{0} has sweet, tart eating taste", name);
}
}

Accessing Base Class Members:

You can use the base keyword to access and call members of the base class, even if those members are hidden or overridden in the derived class.

Example

// Base class (parent class)
public class Fruit
{
public string Color = "Red";
}
// Derive class (child class)
public class Apple: Fruit
{
string Color = "Green";
Console.WriteLine("Apple color is : {0}", base.Color); // Base class field code
Console.WriteLine("Apple color is : {0}", Color); // Derived class field code
}

base keyword in c#

--

--

Shahzad Aslam
Shahzad Aslam

Written by Shahzad Aslam

Welcome to c-sharptutorial.com. I am Shahzad Aslam. I am the founder of c-sharptutorial.com. I'm currently living near Islamabad, Pakistan.

No responses yet