How do you inherit a class into other class in C#?
In C#, you can inherit a class into another class using the concept of class inheritance. To inherit a class, you use the colon (:) symbol followed by the name of the base class after the derived class's name. This establishes an "is-a" relationship, where the derived class inherits the members (fields, properties, methods, etc.) of the base class.
Here's an example of inheriting a class in C#:
public class BaseClass
{
// Base class members
public void BaseMethod()
{
Console.WriteLine("Base method");
}
}
public class DerivedClass : BaseClass
{
// Derived class members
public void DerivedMethod()
{
Console.WriteLine("Derived method");
}
}
class Program
{
static void Main(string[] args)
{
DerivedClass derivedObj = new DerivedClass();
derivedObj.BaseMethod(); // Output: Base method
derivedObj.DerivedMethod(); // Output: Derived method
}
}
In this example, the BaseClass serves as the base class, and the DerivedClass inherits from it. The DerivedClass automatically includes all the public and protected members of the BaseClass, allowing you to access and use them in the derived class.
By creating an instance of the DerivedClass, you can invoke both the inherited method (BaseMethod()) and the method defined in the derived class (DerivedMethod()).
Inheritance is a fundamental concept in object-oriented programming that allows for code reuse, extensibility, and the modeling of relationships between classes. The derived class can add new members, override inherited members, or introduce new functionality while leveraging the existing behavior and structure provided by the base class.