Since Int32 is a value type why does it inherit .ToString()?

*爱你&永不变心* 提交于 2019-12-04 02:10:13

Int32 is a struct and therefore a value type. But:

System.Object
   System.ValueType
      System.Int32

Int32 derives from System.ValueType and this itself derives from System.Object. Et voilà...

Yes, Int32 overrides ToString... although that's somewhat irrelevant here. All types inherit the members of object - you can always call ToString(), you can always call Equals etc. (ValueType overrides Equals and GetHashCode for you, although you should almost always override them further in structs to provide a more efficient implementation.)

Note that you can override the methods yourself very easily:

public struct Foo
{
    public override string ToString()
    {
        return "some dummy text";
    }
}

It's not clear which aspect is confusing you (there are quite a few different areas involved here). If you could clarify, we could address the specific issue.

Perhaps you confusion arises from not realizing that value types inherit from Object? Here is the inheritance graph of System.Object, System.ValueType, System.Int32 and MyNamespace.Customer which is supposed to be a class of you own making. I was lazy and didn't write all the public methods and interfaces of Int32.

ToString is declared in Object but is overriden both in ValueType and in Int32.

The docs are wrong. Both reference and value types inherit that behavior from object (but do remember that not everything in .NET is a class that derives from object).

All (most?) core value types override ToString() to return something more sensible than the class name.

I think the short answer to your question is that value types inherit from System.ValueType and that in turn inherits from object.

Every struct have inheritance from System.ValueType class (not allowed) which is done solely by the compiler. All struct have methods from ValueType base class which is inherited from Object class makes us have access to ToString() and all others.

Even though ValueType is inherited from Object class but it has special implementation of the overrides.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!