Struct Inheritance (No Polymorphism) #9731
-
Struct Inheritance in C#SummaryA proposal to introduce compile-time struct inheritance in C#, allowing structs to inherit fields and methods from other structs through a compile-time expansion mechanism that maintains the flat memory layout and value semantics of structs while reducing code duplication. MotivationCurrently, C# structs cannot inherit from other structs, only implement interfaces. This restriction simplifies memory layout and runtime behavior, but it creates boilerplate in scenarios where one struct conceptually extends another (e.g., Detailed designSyntaxstruct Vector2 : Vector3
{
public float X;
public float Z;
}
struct Vector3 : Vector2
{
public float Z;
} Key Characteristics
ExamplesSimple Vectorstruct Vector2
{
public float X;
public float Y;
}
struct Vector3 : Vector2
{
public float Z;
}
// Desugar to
struct Vector3
{
public float X;
public float Y;
public float Z;
} Method Overridestruct Vector2
{
public float X;
public float Y;
public virtual float Length() => MathF.Sqrt(X * X + Y * Y);
}
struct Vector3 : Vector2
{
public float Z;
public override float Length() => MathF.Sqrt(X * X + Y * Y + Z * Z);
}
// Desugared to
struct Vector3
{
public float X;
public float Y;
public float Z;
public float Length() => MathF.Sqrt(X * X + Y * Y + Z * Z);
public static explicit operator Vector2(Vector3 v) => new Vector2 { X = v.X, Y = v.Y };
}
// Since no `base.` calls exist, hidden base methods are not emitted: Method Override With Base Callstruct Plane
{
public float Width;
public float Height;
public virtual float GetArea() => Width * Height;
}
struct Box : Plane
{
public float Depth;
public override float GetArea() => base.GetArea() * Depth;
}
// Desugared to
struct Box
{
public float Width;
public float Height;
public float Depth;
private float <>Plane_GetArea() => Width * Height;
public float GetArea() => <>Plane_GetArea() * Depth;
public static explicit operator Plane(Box v) => new Plane { Width = v.Width, Height = v.Height };
}
// Hidden base methods are emitted only if referenced. No PolymorphismThis proposal does not introduce polymorphism. Struct inheritance here is strictly a compile-time code reuse feature—derived structs are not subtypes of their base structs, and there is no runtime substitutability or dynamic dispatch.
Drawbacks
Alternatives
Impact of not doing this:
Open questions
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
See: #6270 |
Beta Was this translation helpful? Give feedback.
-
What does this mean? |
Beta Was this translation helpful? Give feedback.
See: #6270