25 Feb 2024
In C#, the base
keyword is used to access members of the base class in the context of a derived class. It is often used to resolve ambiguity when a derived class has a member with the same name as a member in its base class.
Common use cases for the base
keyword:
-
Accessing Base Class Members:
In C#, when a derived class inherits from a base class, it can define its own members, including methods, properties, and fields. If the derived class needs to access a member of the base class with the same name, the
base
keyword allows it to explicitly refer to the base class member.class BaseClass { public void SomeMethod() { Console.WriteLine("BaseClass.SomeMethod"); } } class DerivedClass : BaseClass { public void SomeMethod() { base.SomeMethod(); // Calls the SomeMethod from the base class Console.WriteLine("DerivedClass.SomeMethod"); } }
-
Constructor Chaining:
In object-oriented programming, constructors are used to initialize objects. When a derived class is constructed, it may need to initialize the base class part of the object. The
base
keyword helps in invoking the constructor of the base class from the constructor of the derived class.class BaseClass { public BaseClass(int x) { // Constructor logic } } class DerivedClass : BaseClass { public DerivedClass(int x, int y) : base(x) { // Derived class constructor logic } }
-
Calling Base Class Property or Method from Overridden Member:
In inheritance, a derived class can override methods and properties of its base class. Sometimes, in the overridden method, it's necessary to invoke the method or property of the base class. The
base
keyword is used for this purpose.class BaseClass { public virtual void SomeMethod() { Console.WriteLine("BaseClass.SomeMethod"); } } class DerivedClass : BaseClass { public override void SomeMethod() { base.SomeMethod(); // Calls the overridden method in the base class Console.WriteLine("DerivedClass.SomeMethod"); } }
These are the common scenarios where the base
keyword is used in C# to interact with members or constructors of the base class in the context of a derived class.