C# Tutorial
C# String
C# Array
C# Flow Control
C# Class and Object
C# Inheritance
C# Interface
C# Collection
C# Generic
C# File I/O
C# Delegate and Event
C# Exception
C# Process and Thread
C# ADO.NET Database Operations
In this tutorial, we'll demonstrate how to use the base
keyword in C# to call a method from the parent class. The base
keyword is used to access members of the base class from within a derived class.
Create a new C# Console Application project in Visual Studio.
Create a base class named Animal
with a method called Speak
:
public class Animal { public virtual void Speak() { Console.WriteLine("The animal makes a sound."); } }
Note the use of the virtual
keyword, which allows the Speak
method to be overridden by a derived class.
Create a derived class named Dog
that inherits from the Animal
class and overrides the Speak
method:
public class Dog : Animal { public override void Speak() { // Call the base class Speak method base.Speak(); Console.WriteLine("The dog barks."); } }
In the Speak
method, use the base
keyword to call the Speak
method from the base class Animal
.
In the Main
method, create an instance of the Dog
class and call its Speak
method:
static void Main(string[] args) { Dog myDog = new Dog(); myDog.Speak(); Console.ReadLine(); }
When you run the Console Application, you should see the following output:
The animal makes a sound. The dog barks.
In this tutorial, we've shown you how to use the base
keyword in C# to call a method from the parent class. The base
keyword allows you to access members of the base class from within a derived class, which can be helpful when you need to reuse or extend the functionality of the base class.
C# base keyword example:
base
keyword in C#, which is used to refer to the parent class or base class in an inheritance hierarchy.class BaseClass { public void Display() { Console.WriteLine("This is the base class method."); } } class DerivedClass : BaseClass { public void Show() { // Using base keyword to call parent class method base.Display(); } }
Calling parent class method with base keyword in C#:
base
keyword.class BaseClass { public void Display() { Console.WriteLine("This is the base class method."); } } class DerivedClass : BaseClass { public void Show() { // Using base keyword to call parent class method base.Display(); } }
Calling constructor of base class in C# using base:
base
keyword.class BaseClass { public BaseClass() { Console.WriteLine("Base class constructor called."); } } class DerivedClass : BaseClass { public DerivedClass() : base() { Console.WriteLine("Derived class constructor called."); } }
Override and call base method in C#:
base
keyword.class BaseClass { public virtual void Display() { Console.WriteLine("This is the base class method."); } } class DerivedClass : BaseClass { public override void Display() { Console.WriteLine("This is the derived class method."); // Calling base class method base.Display(); } }