I am more interested in an answer from the .Net and CLR point of view:
Why a struct can not be a base class of another struct or vise versa?
Structs occupy fixed-size slots in the stack (or wherever they're living).
Therefore, you wouldn't be able to do any kind of polymorphism with structs, since the derived struct would be a different size.
It would be possible to inherit members from other structs, but since you wouldn't be able to do any kind of polymprphism, it wouldn't be worth the confusion.
In .net, if class A
inherits from type B
and an object of type A
is passed to code which expects an object of type B
, the passed object would not be converted to a B
but would remain an A
. This is possible because every object has stored with it a reference to a type descriptor. Classes do not have any type descriptors stored with them. If a struct of type A
could be passed by value to a routine expecting a struct of type B
, it would become a struct of type B
. In cases where that would be sensible, it would be more practical to define a widening conversion operator from type A
to B
.
There are times it might be useful to pass a struct of type A
by reference to a routine expecting type B
. Conversion operators wouldn't help there. That could however be handled, albeit somewhat awkwardly, by having struct type A
contain nothing but a field of type B
. That field could then be passed by reference to the routine expecting type B
; the difficulty would be that one would have to include the name of the inner struct in any field accesses.
What would be helpful, not just for structs but for classes as well, would be the concept of an 'extension type'. All classes, whether inheritable or not, could be extended with an extension type, which would include only instance members; variables or values of an extension type would be regarded as run-time objects of the base type, and all conversions between extension types and their base types, or between extension types derived from the same base type would be considered 'widening' and would be processed as no-ops. The only effect of an extension type would be to bring into scope members defined for that type. These would behave much like extension methods, except that they would only apply to variables and variables declared as the extension type, and the members of extension types would have priority over the base class members. One can imagine many uses for such things (in cases where one would like to use extension methods on some instances of a class, but may not want them available on all instances), but as yet no language I'm aware of supports such a feature.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With