Inheritance in C# is a fundamental object-oriented programming concept that allows a class (called a child or derived class) to inherit fields and methods from another class (called a parent or base class). This mechanism promotes code reusability and establishes a hierarchical relationship between classes.
In C#, inheritance can take several forms, including single inheritance (where a class inherits from one base class) and multiple inheritance (though C# supports multiple inheritance through interfaces).
When a class inherits from another class, it can use the members (attributes and methods) of the base class as if they are defined in the derived class. This allows for the creation of new classes that have more specific behaviors based on the base class.
Here's a simple example of inheritance in C#:
// Base class
class Animal
{
public void Speak()
{
Console.WriteLine("Animal speaks");
}
}
// Derived class
class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Dog barks");
}
}
// Usage
class Program
{
static void Main(string[] args)
{
Dog myDog = new Dog();
myDog.Speak(); // Inherited method
myDog.Bark(); // Local method
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?