Why can't a C # structure be inherited?

I read the CLR through C # by Jeffrey Richter, and he says that structure is a value type and cannot be inherited. Why not? Any technical reasons? Or philosophical?

+69
c #
Feb 22 2018-10-22
source share
3 answers

Edit: There are serious editorial concerns about this post, apparently. See comments section.

A bit of both.

Philosophically , this works - there are classes that are the "real" building block for object-oriented programming, and there are structures that are lightweight data types for storage, but allow you to use objects. The method is familiar and convenient.

Technically , a β€œvalue type” means that the entire structure β€” all its contents β€” is (usually) stored wherever you have a variable or member of that type. As a local parameter or function parameter, this means on the stack. For member variables, this means that they are stored in their entirety as part of the object.

As a (basic) example of why inheritance is a problem, consider how storage is affected at a low level if you allow structures to have subtypes with lots of members. Everything that stores this type of structure will occupy a variable amount of memory, based on which of the subtypes it contained, which would be a distribution nightmare. An object of this class will no longer have the specified size at compile time, and the same will be true for the stack frames of any method call. This does not happen for objects that have storage allocated on the heap, and instead have references to a constant value for that storage on the stack or inside other objects.

This is just a high level intuitive explanation. See comments and other answers for extended and more accurate information.

+75
Feb 22 '10 at 10:15
source share

Since the structures are represented in .NET. They are value types and value types that do not have a method table pointer that allows inheritance.

+32
Feb 22 '10 at 10:11
source share

You can find answers to SO Question Why are .NET value types closed? . It @logicnp refers to ECMA 335 , which states:

8.9.10 Inheritance of value type

  • [...]
  • Will be closed to avoid separation problems.
  • The stricter rules specified here provide a more efficient implementation without serious compromise.
+14
Feb 21 2018-11-11T00:
source share



All Articles