In c#, Struct can't inherit a class then why it is implicitly inheriting System.Object where System.Object is a class.
I know System.Object is the base type of every type. But since by definition , Struct can't inherit a class then why System.Object is inherit ?
But since by definition , Struct can't inherit a class
That's a false premise. A custom struct must inherit directly from System.ValueType
, which itself inherits from System.Object
. That is the requirement. It cannot inherit from any other type. So not only can a user defined struct inherit from a class, it in fact must inherit from [a specific] class.
(Note that enums must inherit from Enum
, not Object
, although Enum
inherits from ValueType
, which inherits from Object
.)
In c#, Struct can't inherit a class
Yes, they cannot inherit from a Custom class
, especially being a Value type
, since they can only have operations allowed for the Value types
like:
Stack
, unlike Heap
for the reference types Value Type
, new allocation is made, as in case for primitive types, like Integer
, Float
, so Struct s1 = s2
, creates a brand new copy, but for reference type, it is copy of Reference, which means pointer to same memory Main point, then why allow to derive from
System.Object
class, multiple important reasons:
System.Object
and can thus be represented in a unified manner Value types
are still primitive in operation and capability as compared to Reference types
and has limitation of what they can represent, that's a why a base type is reference type, so that when the need be, conversion can be done via boxing, do allocation on heap and use the functionalities of a reference type System.Object
on all the types, value and reference like ReferenceEquals, GetHashCode, MemberwiseClone,ToString,GetType
, though certainly post overriding
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.