What is difference between Convert.tostring and .tostring() method ?

Most of developers know how to use these methods to convert a type to string, but when it comes to differentiate  these methods  they usually can't express the answer.

Today we will learn the main difference between these two.

In most of articles you will find a common answer that Convert.tostring handles NULL where  .tostring() can't.

Then the question is that  why .tostring() has been implemented  when Convert.ToString() is doing all the jobs effectively.

Convert.tostring() method convert a type to String type (type conversion occures) where .ToString() represent a type to string type if a type not able to represent in string then it will throw exception.(no type conversion occurs).
// Comment
//Returns a null reference exception 
string mystring;
string str = null;
mystring= str.ToString();

//Returns an empty string for str and does not throw an exception. 
string str;
string s= null;
str = Convert.ToString(s);
Actually .ToString()  is used to  represent  a  object into string representation by overridding .ToString() method. Here is the example-


In above example line Console.WriteLine(obj) is writing a object which is not acceptable,but as we are overriding the .ToString() method it will format that object into string representation as written in line string.Format("[{0}, {1}]", _a, _b);

Hope you like the tutorials.

Thanks. 


What is difference between Convert.tostring and .tostring() method ? What is difference between Convert.tostring and .tostring() method ? Reviewed by CodiBucket on 08:54 Rating: 5

No comments:

Facebook

Powered by Blogger.