tags:

views:

317

answers:

2

I am reading CLR via C# by Jeffery Richter and it says a struct is a value type and cannot be inherited. Why not? Any technical reasons? Or philosophical ones?

+14  A: 

Because it is the way structs are represented in .NET. They are value types and value types don't have a method table pointer allowing inheritance.

Darin Dimitrov
One might add: And the reason why they don't have a method table pointer is because value types are designed to be as lightweight as possible.
bitbonk
+16  A: 

A little of both.

Philosophically, it works out - there are classes, which are the "real" building block for object oriented programming, and there are structs, which are lightweight data types for storage but allow object-like method calls for familiarity and convenience.

Technically, being a "value type" means that the entire struct - all of it's contents - are stored wherever you have a variable or member of that type. As a local variable or function parameter, that means on the stack. For member variables, that means stored entirely as part of the object.

That means that if you allowed structs to have subtypes with more members, anything storing that struct type would take up a variable amount of memory based on which subtype it ended up containing, which would be an allocation nightmare. An object of a given class would no longer have a constant, known size at compile time and the same would be true for stack frames of any method call. This does not happen for objects, which have storage allocated on the heap and instead have constant-sized references to that storage on the stack or inside other objects.

Jesse Millikan
Thanks, Jesse. Your explanation gave me some sparks. As to my understanding, OOP comes at a cost. If there's only "ref-type" and everything happens on the heap, whose management is far less efficient than the stack, the performance will be poor. So there comes the so-called "value-type" which lives on the stack for better performance, and it is because of the place of the allocation and further the memory usage paradigm that make the value-type sealed.
smwikipedia
...and if we can figure out a brand-new paradigm of using memory besides stack and heap, maybe new data types will arise.
smwikipedia
As to brand-new paradigms of using memory... It's doubtful. :) Any other paradigm of using memory is likely to be layered on top of stack or heap allocation or both. (Such as closures in functional languages, which might be worth your time to understand.)
Jesse Millikan