开发者

Value types inherit from System.Object...why? [duplicate]

This question already has answers here: 开发者_开发知识库 Closed 12 years ago.

Possible Duplicates:

Is everything in .NET an object?

How do ValueTypes derive from Object (ReferenceType) and still be ValueTypes?

Hi, I just do not get it. System.Object is (I think) reference type but all data types in .NET inherit from it. Also value types do as well. I do not understand it - value type has its value on the stack but its inherited from Object? Hope anyone could help me to understand


You are correct that, while Object is a reference type, value types do inherit from it implicitly, as stated on msdn's reference for Value Types (according to the reference, they technically inherit from the ValueType class, which in turn inherits from Object.

C# made a special case for this so value types can benefit from Object's methods (like ToString) and properties. Also, this way, you can treat value types just like other reference types--nothing stopping you from plugging in an int inside an array of Objects.


Ask yourself why you think it's strange that a type that is typically allocated on the stack would inherit from System.Object and I think you'll find you can't formulate a good reason.

If you think it's because an object's type defines where it is allocated, you're mistaken. What member of ValueType is responsible for defining its allocation mechanism? (What member of System.Object, for that matter?)

Type inheritance in .NET is supposed to comprise "is a" relationships: a string is an object, for example. Everything in the .NET world is an object, so an int is an object, a double is an object, etc.

You can think of this in terms of the Liskov substitution principle: if I write code that expects an object, I should be capable of dealing with any type that is an object—i.e., anything at all. My code should be equally comfortable with a string, an int, a List<int>, etc.

Also note that object guarantees certain members that all types have as a consequence of this: GetType, ToString, and GetHashCode.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜