Basic Difference Between Convert.ToString() And .ToString() Method In C#
Both these methods are used to convert a string. But yes, there is a difference between them and the main difference is that Convert.Tostring() function handles the NULL while the .ToString() method does not and it throws a NULL reference exception.
So, it is a good programming practice to use Convert.ToString() method. But when you want to get an exception if you don't expect your object to be NULL, you must use the .ToString() method.
- //Below code will throw null reference exception.
- object obj = null;
- string str = obj.ToString();
- //Below code will not throw an exception and will return String.Empty
- object obj = null;
- string str = Convert.ToString(obj);
I hope this clears up the basic difference between Convert.ToString() and .ToString() Method in C#.
Comments
Post a Comment