Why can't Struct be obtained from another structure?

I'm more interested in the answer in terms of .Net and CLR:

Why can't a structure be a base class of another structure, or vice versa?

+7
source share
2 answers

Structures occupy fixed slots on the stack (or where they live).

Therefore, you cannot make any polymorphism using structures, since the derived structure will be of a different size.

It would be possible to inherit members from other structures, but since you could not carry out any polygraphism, it would not be worth the confusion.

+12
source

In .net, if class A inherits from type B and an object of type A is passed to code that expects an object of type B , the passed object will not be converted to B , but A will remain. This is possible because each object stores a reference to a type descriptor with it. Classes do not have type descriptors stored with them. If a structure of type A can be passed by value to a procedure that expects a structure of type B , it will become a structure of type B In cases where this would be reasonable, it would be more appropriate to define an extended conversion operator from type A to B

It is sometimes useful to pass a structure of type A reference to the usual pending type B The conversion operators did not help there. However, this could be accomplished, although it is somewhat inconvenient, since type struct A contains only a field of type B This field can then be passed by reference to the expected type B ; the difficulty would be to include the name of the internal structure in any call to the field.

What would be useful not only for structures, but also for classes, would be a concept such as extension. All classes, whether inherited or not, can be extended using an extension type that will include only instance members; variables or values ​​of the extension type will be considered 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 will be considered “expandable” and will be treated as no-ops . The only effect of an extension type is to add the scope defined for that type to members. They will behave just like extension methods, except that they will only apply to variables and variables declared as extension types, and extension type members will take precedence over base class members. You can imagine many uses for such things (in those cases where you would like to use extension methods in some instances of the class, but you might not want them to be available in all instances), but so far the language does not know about the support for such a feature.

+1
source

All Articles