views:

113

answers:

2

Hello all,

While looking at the System.Type class under the Code Definition Window, I cannot seem to understand how an instance of this class is implicitly cast to string. For example, on the following code:

int foo = 0;
Console.WriteLine("Hi! I'm a type of type {0}", foo.GetType());

How was the System.Type resulting from GetType() implicitly cast to string?

+1  A: 

My guess is that this is just calling the ToString()-Method, or another (if defined by the type) conversion method.

Bobby

Bobby
ToString() does not necesarilly gets called automatically for every class
Carlos Muñoz
+4  A: 

It's not being implicitly cast to string. It's being converted to Object (with the standard implicit reference conversion), and String.Format is formatting it appropriately - by calling ToString in this case.

This is not being done at compile-time. The code you've shown calls the Console.WriteLine(string, object) overload.

Jon Skeet
Love the Tony reference
johnc
@lagerdalek: I think I'm going to retire Tony some time this week, and go back to being me.
Jon Skeet
Duh, yeah it's calling one of the overloaded WriteLine() methods. Thanks for pointing that out. Missed that, I read it as Console.WriteLine("blablah"+foo.GetType()); Now, we would prolly get a compile error there...hmm.
Wim Hollebrandse
No, we wouldn't - because of the way string concatenation works. That's a different question though :)
Jon Skeet
Exactly, but it's the question I was reading! :-)
Wim Hollebrandse
gotcha. Thanks.
Krugar