开发者

Difference between Convert.ToString() and .ToString() in C#? [duplicate]

This question already has answers here: Close开发者_如何学运维d 11 years ago.

Possible Duplicate:

variable.ToString() vs. Convert.ToString(variable)

What is the difference between Convert.ToString() and .ToString() in C#?

When I try and convert dataRow[i] to a string using ToString() then I receive an error. How do I fix this?


Basically both are used to convert a value to a String but there is a basic difference between them:

When we have an NULL object, Convert.ToString(Object); handles the NULL value whereas Object.ToString(); does not handle the NULL value and it throws NULL Reference Exception.


There is a simple but important difference between them…

ToString() raise exception when the object is null

So in the case of object.ToString(), if object is null, it raise NullReferenceException.

Convert.ToString() return string.Empty in case of null object

(string) cast assign the object in case of null

So in case of MyObject o = (string)NullObject;

But when you use o to access any property, it will raise NullReferenceException.

http://maniish.wordpress.com/2007/10/08/difference-between-tostring-vs-converttostring-vs-string-cast/


First, Object.ToString() is a virtual function in the base class Object. Any class can override ToString() to provide its own implementation. Convert.ToString() is a static method that attempts to take many different arguments and convert them into a meaningful string. Also, Object.ToString() will fail if the object calling it is null.

In addition, Object.ToString() does not always convert the object to the string form that you might expect. For instance, the base function Object.ToString() will always return the fully qualified type name of the object. Any class may implement ToString() however it wishes and this does not necessarily have to be something meaningful.


There is a basic different between Convert.ToString and .Tostring. Convert.ToString will handle the Null exception but .Tostring will throw error

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜