In Visual Studio, I have a class “Program” with a method “Main”. Inside this main method I have a field called name of type string in which I have assigned a value “Some Name”.
To print this name on the console screen, we can say:
Console.WriteLine(name);
Run the application.
Now let’s say for some reason we passed the value as null for the name field.
But before displaying this name on the console, we need to convert this null into a string and for that we can use Convert.ToString and ToString method.
So, here first we are converting the name field using Convert.ToString and then using ToString method.
Run the application.
The output using Convert.ToString method displays a blank line but output using ToString method throws an un-handled exception.
Difference
Convert.ToString handles null while ToString doesn’t and throws a NULL reference exception.
Note
An instance method ToString cannot be called or used on a null object.
I hope you like it. Thank you