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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With