Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whose ToString() would be called?

Tags:

.net

boxing

As we know, int has ToString() method which override the ToString() method of base type Object.

For this following code,

int x = 100;
object y = (object)x;
Console.Write(y.ToString());

(1) Whose ToString() would be called? int or object? WHY?
(2) How we can check/view the truth? By any debug/tool?

like image 883
user1033098 Avatar asked Aug 02 '12 06:08

user1033098


1 Answers

Int32.ToString() would be called, because ToString() is called virtually. Int32.ToString() overrides Object.ToString(), so at runtime it effectively replaces Object.ToString().
And at runtime, y is a boxed int.

like image 171
Botz3000 Avatar answered Nov 27 '22 12:11

Botz3000