Showing posts with label Difference Between .ToString() and Convert.ToString() in C#. Show all posts
Showing posts with label Difference Between .ToString() and Convert.ToString() in C#. Show all posts

Thursday, February 26, 2015

Difference Between .ToString() and Convert.ToString()

This is a very important question which usually ask in the interviews.

Let us discuss-

Answer- This question have very simple answer that .Tostring() can’t handle the null value but Convert.ToString can.

Example 1- understand it with the help of program.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication2
{
    public partial class Test : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
          
            Session["Name"] = null;
            string Name=Session["Name"].ToString();

          }
    }
}



Explanation- We can see in above example that there is a session which have null value, when we apply .ToString() it will throw Exception ‘object reference not set to an instance of an object’


Example 2-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication2
{
    public partial class Test : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
          
            Session["Name"] = null;
            string Name= Convert.ToString( Session["Name"]);

          }
    }
}

Explanation- We can see in above example that there is a session which also have null value, when we apply Convert.ToString it will not  throw Exception, it will handle it and sting ‘Name’ have  empty string.




                                                      Author- Er. Rahul Kr. Yadav