ToString() and (string) cast

  • Thread starter Thread starter John Wood
  • Start date Start date
J

John Wood

If you override ToString(), why can't the default implementation of the
string cast use that implementation for the object? It's a question people
ask me time and time again.
 
Hi Jhon,

ToString() returns only a value, which is representing the object like
int.ToString() returns the value as a string or somtemis it returns the type
or name or somethin else.

with the cast (string) you cast the object into a string object.

--
Mit freundlichen Grüßen -- Regards

Ralph Gerbig
www.ralphgerbig.de.vu
(e-mail address removed)
 
Right, but seeing as there's little difference between (string)3 and
3.ToString() -- I don't see why the compiler can't choose to use ToString()
when no string cast is available in the former example.
 
string msg;
int i = 5;
object o;

msg = i.ToString(); // Kopies the value i has into msg
msg = (string)i; // Trys to cast i into a string object and copy a pointer
into msg (this statement won't work)
o = msg; // copys a pointer on msg into o (no explicit cast is needed
because string is inherited from System.Object)

there is a huge diference in copying a pointer and changing a value.

--
Mit freundlichen Grüßen -- Regards

Ralph Gerbig
www.ralphgerbig.de.vu
(e-mail address removed)
 
I see what you're saying. There's no hierarhical relationship between an int
and a string, and that's what casting is for. So I suppose ToString() is
really just a conversion routine, not a casting routine.

Thanks for clarifying.
 
string msg;
int i = 5;
object o;

msg = i.ToString(); // Kopies the value i has into msg
msg = (string)i; // Trys to cast i into a string object and copy a pointer
into msg (this statement won't work)

The difference that your comments describe does not exist. Both
ToString() and (string) generate a System.String that is (hopefully)
somehow based on the value of i. The second statement would work just
fine if i happened to be of a type that defines a typecast to string.

John Wood is correct, there really is no difference between the two
operations, and the compiler might easily map the string cast to the
ToString method by default.
 
I think one consideration against such a default mapping is that some
objects might not really *want* to be able to be cast to a string. If there
isn't a possible string representation of the object, it makes sense that
the object wouldn't like to be cast to a string. ToString exists mainly, I
think, so that *any* object can be represented at least *minimally* as a
string. But the presence of a string cast implies as a matter of design that
the casted object is somehow a complete or adequate representation of that
object, which is not always possible, and less often the case.

Chris
 
Back
Top