Therefore, when you try Convert.ToString() on a custum object, you are guaranteed not to get an ObjectReferenceNullException. On the other hand you might want to get an exception if you don't expect your object to be null.
Just to give an understanding of what the above question means seethe below code. int i =0; MessageBox.Show(i.ToString()); MessageBox.Show(Convert.ToString(i)); We can convert the integer “i” using “i.ToString()” or “Convert.ToString” so what’s the difference. 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.
What is the difference between Convert.toString and .toString()
What is the difference between Convert.toString and .toString()
GeoComeProgrammer
Kuju is absolutely correct.But what will happen if tostring is to be used with an custom object
JCollins
public static string ToString(object value, IFormatProvider provider)
{
IConvertible convertible = value as IConvertible
if(convertible != null)
{
return convertible.ToString(provider)
}
if(value != null)
{
return value.ToString();
}
return string.Empty
}
Therefore, when you try Convert.ToString() on a custum object, you are guaranteed not to get an ObjectReferenceNullException. On the other hand you might want to get an exception if you don't expect your object to be null.
Bravo_00
There is no difference between i.ToString() and Convert.ToString(i).
This is the body of the Convert method:
public static string ToString(int value)
{
return value.ToString();
}
Furthermore, the integer variable cannot be null since its a value type.
Helio Gomes
int i =0;
MessageBox.Show(i.ToString());
MessageBox.Show(Convert.ToString(i));
We can convert the integer “i” using “i.ToString()” or “Convert.ToString” so what’s the difference.
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.