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.
Casting is changing the type of the variable. Parsing is 'examining' the string and assigning its logical value to some variable.
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.
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.
The basic difference between them is Convert
function handles NULL
s while i.ToString()
does not. It will throw a NULL
reference exception error. So, as good coding practice using
Convert
is always safe.
myObject.ToString()
could throw a NullReferenceException
, where Convert.ToString
will never do that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With