Sunday, August 5, 2012

Difference Between ToString() vs Convert.ToString()


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.
Example : int i =0;    MessageBox.Show(i.ToString());        MessageBox.Show(Convert.ToString(i));
We can convert the integer “i” using “i.ToString()” or “Convert.ToString” so what’s the difference.
The basic difference between them is “Convert” function handles NULLS while “i.ToString()”
does not it will throw a NULL reference exception error. So as good coding practice using
“convert” is always safe.


Code Sample :

C#
    public String FullName = null;
    protected void Page_Load(object sender, EventArgs e)
    {

        try
        {
            Response.Write("<b>.ToString</b><br>");
            Response.Write("FullName :" + FullName.ToString());
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }

        Response.Write("<br><br>");

        try
        {
            Response.Write("<b>Convert.ToString</b><br>");
            Response.Write("FullName :" + Convert.ToString(FullName));
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }

    }

                         OutPut:

No comments:

Post a Comment