Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between converting strings [duplicate]

Tags:

string

c#

Possible Duplicate:
Difference between Convert.tostring() and .tostring()

Hi

Carrying on from this question What is the difference between Convert and Parse?

Here are two lines of code.

Convert.ToString(myObject);
myObject.ToString();

My question is what is the difference and which would be best to use?

Thank you in advance.

like image 336
Ash Burlaczenko Avatar asked Aug 17 '10 08:08

Ash Burlaczenko


People also ask

What is the difference between cast and parse?

Casting is changing the type of the variable. Parsing is 'examining' the string and assigning its logical value to some variable.

What is the difference between parse and convert in C#?

Parse and Convert ToInt32 are two methods to convert a string to an integer. The main difference between int Parse and Convert ToInt32 in C# is that passing a null value to int Parse will throw an ArgumentNullException while passing a null value to Convert ToInt32 will give zero.

What is the difference between parsing and type casting in Java?

Casting means taking a variable of one type and turning it to another type. There are obviously some combinations which can be cast, and some which cannot. Parsing means reading text and deciding what the different parts of it mean.


2 Answers

The basic difference between them is Convert function handles NULLs while i.ToString() does not. It will throw a NULL reference exception error. So, as good coding practice using Convert is always safe.

like image 161
Neil Knight Avatar answered Sep 26 '22 23:09

Neil Knight


myObject.ToString() could throw a NullReferenceException, where Convert.ToString will never do that.

like image 44
leppie Avatar answered Sep 26 '22 23:09

leppie