'base' keyword magic in c#

 In C#, the base keyword is used to refer to members of a base (parent) class within a derived (child) class. It’s particularly useful in inheritance scenarios where a derived class needs to call a constructor, method, or property in the base class. Here’s how base is typically used:

  1. Calling Base Class Constructors: The base keyword can be used in a derived class constructor to call a specific constructor of the base class. This is done by following the derived class constructor definition with : base(parameters). This is useful if the base class has constructors that need specific parameters.


    public class Animal { public Animal(string name) { /*...*/ } } public class Dog : Animal { public Dog(string name) : base(name) { /*...*/ } }
  2. Accessing Base Class Members: In a derived class, you can use base to access members (methods, properties, fields) of the base class that are hidden by similarly named members in the derived class. This is useful for accessing the base implementation of an overridden method.


    public class Animal { public virtual void MakeSound() { Console.WriteLine("Animal sound"); } } public class Dog : Animal { public override void MakeSound() { base.MakeSound(); // Calls the MakeSound method in Animal Console.WriteLine("Dog barks"); } }
  3. Using base to Avoid Name Conflicts: If a derived class has members with the same name as members in the base class, base can differentiate between the two.

Comments

Popular posts from this blog

Performance Optimization in Sitecore

Strategies for Migrating to Sitecore from legacy or upgrading from older Sitecore

Azure Event Grid Sample code