Do value types (Integer, Decimal, Boolean, etc…) inherit from Object?

前端 未结 8 2048
梦谈多话
梦谈多话 2020-12-03 14:59

Looking for clarification on this...

I\'ve heard that \'everything\' in .Net inherits from Object. I\'ve also heard that the difference between value types and refe

相关标签:
8条回答
  • 2020-12-03 15:20

    Value types, such as Int32, are structs.

    From the VS 2008 C# help file (since I had it open) on structs:

    A struct cannot inherit from another struct or class, and it cannot be the base of a class. All structs inherit directly from System.ValueType, which inherits from System.Object.

    0 讨论(0)
  • 2020-12-03 15:21

    It depends on how you view the terminology - which depends on whether you're talking about C# or the CLI spec. For example, in the CLI spec (ECMA-355) sections 8.9.8 and 8.9.10 state:

    Value types do not inherit, although the associated boxed type is an object type and hence inherits from other types.

    and

    In their unboxed form value types do not inherit from any type. Boxed value types shall inherit directly from System.ValueType unless they are enumerations, in which case, they shall inherit from System.Enum. Boxed value types shall be sealed.

    So from the CLI's point of view, the answer to the question is no.

    However, let's look at the C# spec - and as we're in an ECMA-like mood, let's go for that version (which is currently stuck at C# 2). Section 11.1.1 states:

    All value types implicitly inherit from the class System.ValueType, which, in turn, inherits from class object.

    So from the C# specification's point of view, the answer is yes.

    One could argue that you tagged your question ".net" so we should use the CLI definition; if you'd tagged it "c#" we should have used the C# definition. See how arbitrary it is? :)

    All of this spec-diving isn't to much practical purpose though. The answer depends on the intricacies of definitions. It's more sensible to construct some interesting situation where it matters... so what do you want to do? If you can present some code, we can answer questions about what will happen - and that's more important than definitions.

    (Yes, this is unusual for me - in general, terminology matters a lot to me. In some cases, however, the subtleties are more of a curse than a blessing.)

    0 讨论(0)
提交回复
热议问题