Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

These are the docs about .ToString() that has prompted this question. They state:

Because Object is the base class of all reference types in the .NET Framework, this behavior [.ToString()] is inherited by reference types that do not override the ToString method.

Yet further on it goes to state:

For example, the base types such as Char, Int32, and String provide ToString implementations

However Int32 is a struct and hence must be a value type.

So what's going on here? Does Int32 implement it's very own .ToString() which has nothing to do with Object?

like image 736
m.edmondson Avatar asked Nov 16 '11 13:11

m.edmondson


3 Answers

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à...

like image 167
Anja Avatar answered Oct 08 '22 11:10

Anja


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.

like image 33
Jon Skeet Avatar answered Oct 08 '22 11:10

Jon Skeet


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.

UML

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

like image 38
Martin Liversage Avatar answered Oct 08 '22 12:10

Martin Liversage