The basic difference between the 2 methods is
- Convert.ToString() can handle NULL
- .ToString() does not handle NULL
Let's test this out. In the below code snippet, we have a string object which is set to a value of NULL.
Code Snippet
class Program
{
public static void Main()
{
string name = null;
Console.WriteLine("Convert.ToString output is = " + Convert.ToString(name));
Console.WriteLine(".ToString output is = " + name.ToString());
Console.Read();
}
}
Output
Convert.ToString output is =
Unhandled Exception:
System.NullReferenceException: Object reference not set to an instance of an object.
at test.console.Program.Main() in C:\DevTo\ToString\Program.cs:line 14
The .ToString() method cannot handle NULLs and throws a NullReferenceException
.
Let me know in the comments what do you use between these two :)
Follow me on https://www.instagram.com/thedotnetweekly for more such posts.
Top comments (2)
Convert.ToString
certainly handles null elegantly, but we can control null coalescence with the instance method too.That is true Sean.Unfortunately, the most common mistake I have seen people do is even after being aware of this and forget to put it until an exception is thrown on production :)