Difference between .ToString() and Convert.Tostring() in .NET

Difference between .ToString() and Convert.Tostring() in .NET

 

The Major Difference between .ToString() and Convert.Tostring() is about NULL Exception.

The ToString() fails Converting object to string when the object is null.

We get error when the Object is NULL.

 

The Convert.Tostring() handle the NULL Object.

Convert.Tostring()handles null and not throws ObjectReferenceNullException.
Tostring() does not handles the null value and throws the null exception error message.

Here’s an example

.NET C#

public String YourName = 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(“Your Name :” + Convert.ToString(YourName));

}
catch (Exception ex)
{

Response.Write(ex.Message);

}

}

 

The RESULT is :

Tostring()
Object reference not set to an instance to an object.

Convert.Tostring()
YourName:

Leave a Reply

Your email address will not be published. Required fields are marked *

9 + 1 =


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">