Sunday, June 28, 2009

Tech Tip:Tostring() vs Convert.Tostring()

We normally use the .Tostring() or Convert.Tostring() functions in day to day coding. Although the function of two methods are same but It’s important to understand the behavior of the methods in determining which to use.

When using the Convert.ToString() on a string value it simply returns the value, the ToString() on a sting returns this (a reference to the string itself).
When called on an object, the Convert.ToString() will try to convert it an IConvertible interface first, if this fails and the object is not null it will call the ToString on the object. If the object reference is null it returns an empty string.

The default behavior of the ToString method on an object is to return the name of the type (this.GetType().ToString()) . Calling the ToString() method directly has less overhead but you need to perform a null test prior to calling any methods on the object.

So, it’s clearly advantageous to use the Convert.Tostring() instead of ToString() as it will eliminate need to check for null prior to conversion.


Happy coding !!!!
Vinod

No comments: