base keyword in C#
Base
keyword in C#:
In C#, the base
keyword is used to access members of the base class from within a derived class.
Accessing Base Class Members: Allows access to methods, properties, and fields of the base class that are not overridden in the derived class.
Calling Base Class Constructors: Used to call the base class constructor from within the derived class constructor. This ensures that the base class is properly initialized.
Overriding and Hiding Members: When a member in the derived class overrides or hides a member in the base class,
base
can be used to access the overridden or hidden member.
Accessing Base Class Members:
public class BaseClass
{
public void Display()
{
Console.WriteLine("BaseClass Display");
}
}
public class DerivedClass : BaseClass
{
public void Show()
{
base.Display(); // Calls Display() of BaseClass
}
}
Calling Base Class Constructors:
public class BaseClass
{
public BaseClass(string message)
{
Console.WriteLine(message);
}
}
public class DerivedClass : BaseClass
{
public DerivedClass() : base("Hello from BaseClass")
{
// Additional initialization for DerivedClass
}
}
Overriding and Hiding Members:
public class BaseClass
{
public virtual void Display()
{
Console.WriteLine("BaseClass Display");
}
}
public class DerivedClass : BaseClass
{
public override void Display()
{
base.Display(); // Calls the Display() of BaseClass
Console.WriteLine("DerivedClass Display");
}
}
Comments
Post a Comment