using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExampleOfString
{
class Program
{
static void Main(string[] args)
{
String UserName = null ;
try
{
//Below statement WILL THROW an exception as .ToString() does not handles null values
String strUserId = UserName.ToString();
}
catch (NullReferenceException ex)
{
Console.WriteLine("Error:{0}", ex.Message);
}
try
{
//Below statement WILL NOT THROW an exception as convert.tostring handles implicitly
String strUserId = Convert.ToString(UserName);
Console.WriteLine("UserName:{0}", strUserId);
}
catch (NullReferenceException ex)
{
Console.WriteLine("Error:{0}", ex.Message);
}
}
}
}
/*
Below is the output of the console application
Error:Object reference not set to an instance of an object.
UserName:
Press any key to continue . . .
*/
A look at the difference between Convert.ToString() and .ToString() method.
Below example clears the confusion between the usage of both the method. Thus developers will it appropriately


Join the conversation! Your thoughts help the community grow.