Sobes.tech
Middle+

Why can't a struct inherit?

sobes.tech AI

Answer from AI

In C#, a struct is a value type, and a class is a reference type. Structures do not support inheritance because:

  • Inheritance implies polymorphism and virtual methods, which require additional memory and management through pointers, contradicting the lightweight value concept of structs.
  • A struct cannot have a base class (except for implicit inheritance from System.ValueType) to avoid complexities with memory management and performance.

If inheritance is needed, a class should be used. Structs are intended for small, immutable objects where performance and minimizing allocations are important.

Example:

struct Point
{
    public int X;
    public int Y;
}

// Cannot do
// struct ColoredPoint : Point {}
Why can't a struct inherit? — C# - sobes.tech