Different between [ToString()],[Convert.Tostring()] and [(string)variable] in C#
Asked
Active
Viewed 227 times
0
-
2Does this answer your question? [Difference between Convert.ToString() and .ToString()](https://stackoverflow.com/questions/2828154/difference-between-convert-tostring-and-tostring) – jalsh Feb 20 '20 at 05:45
-
Convert.ToString() **CAN** handle null values and .ToString() will not. – styx Feb 20 '20 at 05:47
-
`(string)3` will fail, while `3.ToString()` will work – Hans Kesting Feb 20 '20 at 07:27
1 Answers
0
int A =0;
MessageBox.Show(A.ToString());
MessageBox.Show(Convert.ToString(A));
Here both the methods are used to convert the string but 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. (string)casting is only to convert string and objects.
Let's see another example:
string s;
object o = null;
s = o.ToString();
//returns a null reference exception for s.
string s;
object o = null;
s = Convert.ToString(o);
//returns an empty string for s and does not throw an exception.
static void Main(string[] args)
{
try
{
string s;
object o = null;
s = (string)o;
Console.WriteLine(s);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.ReadKey();
}
//returns an empty string for s and does not throw an exception.

Bibin
- 492
- 5
- 11
-
This is not the difference, this is just what they do in a particular circumstance, and its fairly suspect for the most part – TheGeneral Feb 20 '20 at 05:58