C# Base
To access fields, constructors and methods of the base class in C#, the base keyword is used within an instance method, constructor or instance property accessor and not within the static method.
C# base keyword: accessing the base class field:
The base keyword can be used to access the fields of the base class within the derived class. In case the base and the derived classes define the same field, the base keyword is used. It is not required to use the base keyword, in case the derived class doesn’t define the same field. The derived class method can directly call the Base class field.
Example:
using System; public class Flower{ public string color = "red"; } public class Lily: Flower { string color = "white"; public void display() { Console.WriteLine(base.color); Console.WriteLine(color); } } public class flwr { public static void Main() { Lily f = new Lily(); f.display(); } } |
Output:
Explanation:
In the above example, we are using the base keyword to access the fields of the base class.
C# base keyword: calling the base class method:
In C# the base keyword is also used to call the base class method. In case the base and the derived classes define the same method, i.e, the method is overridden, the base keyword is used. It is not required to use the base keyword, in case the derived class doesn’t define the same method. The derived class method can directly call the Base class method.
Example:
using System; public class Flower{ public virtual void color(){ Console.WriteLine("White!!"); } } public class Lily: Flower { public override void color() { base.color(); Console.WriteLine("White color!!"); } } public class flwr { public static void Main() { Lily f = new Lily(); f.color(); } } |
Output:
Explanation:
In the above example, we are using the base keyword to call the method of the base class.
C# inheritance: calling base class constructor internally:
The base class constructor is invoked internally when the base class is inherited.
Example:
using System; public class Flower{ public Flower(){ Console.WriteLine("Flower!!"); } } public class Lily: Flower { public Lily() { Console.WriteLine("Lily!!"); } } public class flwr { public static void Main() { Lily f = new Lily(); } } |
Output:
Explanation:
In the above example, we are calling the base constructor internally.