The base keyword lets a derived class access members of its immediate base class. It has three main uses. 1. Calling the base class constructor public class Employee { public string Name { get; } public Employee(string name) => Name = name; } public class Manager : Employee { public decimal Bonus { get; } public Manager(string name, decimal bonus) : base(name) // initialises the base part first { Bonus = bonus; } } If the base class has no parameterless constructor, the derived constructor must call base(...) explicitly. The base constructor always runs before the derived constructor body. 2. Calling the base implementation of an overridden method public class Employee { public virtual decimal CalculatePay() => 50_000m; public virtual string Describe() => $"Employee {Name}"; } public class Manager : Employee { public override decimal CalculatePay() => base.CalculatePay() + Bonus; // extend, not replace public override string Describe() => base.Describe() + " (Manager)"; } This is common when you want to keep the base behaviour and add to it — for example calling base.OnModelCreating(modelBuilder) in an EF Core DbContext, or base.Dispose(disposing) in a dispose pattern. 3. Accessing hidden base members If a derived class hides a member with new, base.Member still refers to the base version: public class Derived : Base { public new string Info => "Derived"; public string BaseInfo => base.Info; } Rules - base can be used only inside instance members (constructors, instance methods, property accessors) — not in static methods. - It refers to the immediate base class; you cannot skip levels (base.base is not allowed). - base calls are non-virtual: base.Method() always calls the base class's implementation, even if the method is overridden further down. Comparison with this - this refers to the current instance; this(...) chains to another constructor in the same class. - base refers to the base class part of the current instance; base(...) chains to a base class constructor.
Ravindra Wadile · · 0 likes