2 Replies - 769 Views - Last Post: 27 October 2012 - 01:37 PM Rate Topic: -----

#1 pcroft  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 27-October 12

What is the difference between .ToString() and (string)variable?

Posted 27 October 2012 - 01:13 PM

What is the difference between using ivariable.ToString() and (string)ivariable? My understanding is that (string)ivariable is recasting the variable. But how does that differ from ToString()?

Thank you for any help.
Is This A Good Question/Topic? 0
  • +

Replies To: What is the difference between .ToString() and (string)variable?

#2 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5522
  • View blog
  • Posts: 11,830
  • Joined: 02-June 10

Re: What is the difference between .ToString() and (string)variable?

Posted 27 October 2012 - 01:18 PM

.ToString() is a method within the class - That's why you see parenthesis.

If you make a custom class (possibly inherited from another class) .NET won't know how to implicitly convert it to a string. So you make (or override) the .ToString() method to provide the exact string you want to return fro your class.


public class Widget
{

   public string ToString()
   {
     // Do some fancy work calculating some value
     // And adding other strings together
     return myFancyCalculatedString;
   }
}

Was This Post Helpful? 0
  • +
  • -

#3 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2262
  • View blog
  • Posts: 9,466
  • Joined: 29-May 08

Re: What is the difference between .ToString() and (string)variable?

Posted 27 October 2012 - 01:37 PM

.ToString has nothing to do with casts. A cast is a an operator.

public static explicit operator Int64(dbInt64 x) 
   {

   }


public static implicit operator Int64(dbInt64 x) 
   {
  
   }



.ToString() is more to do with a textual representation of the information in the object, which why it also has an overloads that takes a IFormatProvider and a FormatString. By default it inherits the .ToString from its base class, and ultimately all object inherit from type Object, which provide (through reflection i think.) the fully qualified name of the object. eg. System.Linq.Enumerable.

This post has been edited by AdamSpeight2008: 27 October 2012 - 01:38 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1