Reputation: 1711
Can a struct be derived from a class in c#?
If not, Why can primitive data types, such as int, be derived from the class object
? Since the data type int is basically a struct type(value type).
Is this just an exception to the rule?
Upvotes: 8
Views: 4323
Reputation: 81115
When the run-time allocates a storage location for a type, or generates code to operate on one, it checks whether the type derives from System.ValueType
but is not System.ValueType
itself. Unless the storage location meets those criteria, it will hold a heap object reference, and any code to operate on its members (fields, methods, properties, etc.) will act upon the referenced object. Otherwise, the storage location will hold all the public and private fields of that type (which will be laid out identically in all storage locations of that type), and any code to operate on its members will operate on the storage location itself.
If an attempt is made to store a value type into a storage location of class ValueType
, or a storage location which does not derive from ValueType
, the system will generate a new heap object of the storage location's type, and then store a reference to that object in the appropriate storage location. Although storage locations of types deriving from System.ValueType
, and code to access them, are treated specially by the run-time, heap object instances which inherit from System.ValueType
(such as the newly-created one just mentioned) are simply heap objects that happen to derive from System.ValueType
, and have inheritance behaviors which are essentially the same as other types, and may thus be passed around by code expecting to deal with heap references.
A statement like Object Foo = New System.Drawing.Point(3,4);
actually involves three kinds of things:
The upshot of all this is that while value types may be defined as inheriting from ValueType
which inherits from Object
, and while heap objects whose types inherit from ValueType
do inherit from Object
, storage locations of value types do not hold things that inherit from Object
.
Upvotes: 1
Reputation: 1828
Integers and other value types (e.g. bool) are objects, because it allows them to leverage inheritance (i.e. they have access to the common .Equals()
, .GetType()
, .ToString()
functions).
It's a design decision in the .NET framework. Rather than writing separate functions for all the value types under System.ValueType, they use a common code base.
Upvotes: 9
Reputation: 6334
The class hiearchy works as follows (simplified):
Object -> ValueType -> int Object -> ValueType -> struct
Structs by definition of c# do not allow inheritance.
Here is a nice article describing the role of stucts within the C# language:
http://msdn.microsoft.com/en-us/library/aa288471(v=vs.71).aspx
Upvotes: 0
Reputation: 887195
All structs inherit System.ValueType
, which in turn inherits Object
.
You cannot change that.
Upvotes: 6