Wednesday, 30 October 2024

What is the purpose of base keyoword in C# ?

In C#, the base keyword is used to access members (fields, properties, methods, and constructors) of a base class from within a derived class. It provides a way for derived classes to call or reference methods, properties, and constructors defined in their base (parent) class.

Here are common scenarios where the base keyword is used:

1. Calling Base Class Constructor

The base keyword can be used in a derived class constructor to call a specific constructor in the base class. This is useful for initializing base class properties or fields.

public class Person { public string Name; public Person(string name) { Name = name; } } public class Employee : Person { public int EmployeeId; public Employee(string name, int employeeId) : base(name) // Calls Person(string name) { EmployeeId = employeeId; } }

2. Accessing Base Class Methods

If a derived class has a method that overrides or hides a method in the base class, base can be used to call the base class’s version of that method.

public class Animal { public virtual void Speak() { Console.WriteLine("Animal sound"); } } public class Dog : Animal { public override void Speak() { base.Speak(); // Calls Animal's Speak method Console.WriteLine("Dog barks"); } }

3. Accessing Base Class Properties and Fields

You can use base to refer to properties or fields in the base class if the derived class has members with the same name, avoiding ambiguity.

public class Vehicle { public int Speed = 60; } public class Car : Vehicle { public int Speed = 100; // Hides Vehicle's Speed public void ShowSpeeds() { Console.WriteLine("Car Speed: " + Speed); Console.WriteLine("Vehicle Speed: " + base.Speed); // Refers to Vehicle's Speed } }

Summary

The base keyword in C# is essential for:

  • Calling the base class constructor.
  • Accessing base class methods, especially when overridden in the derived class.
  • Accessing base class fields or properties that may be hidden by the derived class members.
Share:

0 comments:

Post a Comment