Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

ToString - Different Syntax? 2

Status
Not open for further replies.

GHolden

Programmer
May 28, 2002
852
GB
Hi,

I am very new to C# (started today!). There seems to be two ways to convert an integer variable (in this case x) to a string:

i.e.

MyString = Convert.ToString(x)
MyString = x.ToString()

Can anyone tell me if there is any reason for using one or other method, or are they essentially the same?

Thanks.


There are two ways to write error-free programs; only the third one works.
 
Convert.ToString(myObject) will use one of the ToString methods of System.Convert to produce the result.

myObject.ToString() will use the ToString method of myObject, which the creator of the object can modify to be whatever they like.

For things like ints both methods will produce the same result, but if you wanted to you could (for instance) create your own type based on int that returned "one hundred and forty-three" instead of "143" when you called its ToString method.

I hope I've explained that properly, I'm not that hot on terminology!

Nelviticus
 
Like Nelviticus says -- most of the time you get the same results. But it's possible to override the ToString method in one of your classes (to return something specific to that type), in which case they might not be the same.

Chip H.


____________________________________________________________________
Click here to learn Ways to help with Tsunami Relief
If you want to get the best response to a question, please read FAQ222-2244 first
 
The way I look at it is Convert.xxxx will convert one base datatype to another. datatype.ToString() will give the string representation with no conversion.
Marty
 
Thanks very much both of you. Very helpful.



There are two ways to write error-free programs; only the third one works.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top