.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> C# >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Difference between Convert.ToString() and .ToString() method.

Posted By:shankey       Posted Date: February 02, 2011    Points: 75    Category: C#    URL: http://www.dotnetspark.com  

A look at the difference between Convert.ToString() and .ToString() method.
 

A look at the difference between Convert.ToString() and .ToString() method.

Convert.ToString()

You are guaranteed not to get an ObjectReferenceNullException.

.ToString()

You might want to get an exception if you don't expect your object to be null.

 

Below example clears the confusion between the usage of both the method. Thus developers will it appropriately

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExampleOfString
{
    class Program
    {
        static void Main(string[] args)
        {
            String UserName = null ;
            try
            {
                //Below statement WILL THROW an exception as .ToString() does not handles null values
                String strUserId = UserName.ToString();
            }
            catch (NullReferenceException ex)
            {
                Console.WriteLine("Error:{0}", ex.Message);
            }

            try
            {
                //Below statement WILL NOT THROW an exception as convert.tostring handles implicitly
                String strUserId = Convert.ToString(UserName);
                Console.WriteLine("UserName:{0}", strUserId);
            }
            catch (NullReferenceException ex)
            {
                Console.WriteLine("Error:{0}", ex.Message);
            }
        }
    }
}

/*
Below is the output of the console application

Error:Object reference not set to an instance of an object.
UserName:
Press any key to continue . . .
*/

 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend