It's not possible to inherit from a C# struct. It's not obvious to me why this is:
- Clearly you can't have a reference type that inherits from a value type; this wouldn't work
- It doesn't sound reasonable to inherit from one the primitive types (Int32, Double, Char, etc.)
- You'd need to be able to call (non-virtual) methods on the base using a derived instance. You could cast from a derived struct to the base, since they would overlap the same memory. I guess casting from a base to derived wouldn't work, since you couldn't know the type of the derived struct at runtime.
- I can see that you couldn't implement virtual methods in your class hierarchy, since value types can't have virtual members
I wonder if this is a technical limitation in the CLR, or something that the C# compiler stops you from doing?
Edit: Value types can't have virtual methods, and I realise this limitation rules out most scenarios in which you'd want to use inheritance. That still leaves inheritance-as-aggregation, though. Imagine a Shape
struct with a Colour
field: I can write code that accepts any struct derived from Shape
, and access its Colour
field, even if I can never write a virtual Shape.Draw
method.
I can think of one scenario that would get broken by non-sealed value types. Value types are supposed to implement Equals
and GetHashCode
correctly; even though these two methods on System.Object
are virtual, they get called non-virtually on value types. Even if value types weren't sealed, someone writing a struct derived from another one couldn't write their own implementation of these two methods and expect to have them called correctly.
I should point out that I'm not suggesting I should be able to inherit from structs in my own code. What I am trying to do, though, is to guess why this particular code smell is forbidden by .NET.
Edit 2: I just spotted this very similar question, the answer to which is effectively "because then arrays of value types wouldn't work".