Interfaces and abstract classes are both important concepts in object-oriented programming in C#. They provide a way to define contracts and base functionality which can be implemented or inherited by derived classes.
An interface is a contract that defines a set of methods and properties without implementing them. Any class that implements an interface must provide an implementation for all its members. Interfaces allow for polymorphism and multiple inheritance in C#.
An abstract class is a class that cannot be instantiated on its own and may contain abstract methods (without implementation) as well as concrete methods (with implementation). Abstract classes allow for shared functionality while enabling derived classes to implement their unique behavior.
// Define an interface
public interface IVehicle
{
void Start();
void Stop();
}
// Define an abstract class
public abstract class VehicleBase
{
public abstract void Move();
public void Refuel()
{
Console.WriteLine("Refueling...");
}
}
// Implementing the interface and inheriting from the abstract class
public class Car : VehicleBase, IVehicle
{
public override void Move()
{
Console.WriteLine("Car is moving...");
}
public void Start()
{
Console.WriteLine("Car started.");
}
public void Stop()
{
Console.WriteLine("Car stopped.");
}
}
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?