Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Difference between Convert.ToString() and ToString()

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 352
    Comment on it

    The ToString() method, expects that the object which you invoke in your program should not be Null. If the object is taking null value,then user will get the Null Reference Exception at run time and program will not be executed completely. 

    To understand the difference consider the example below. we have just defined a property Name in the student class. But we do not set any value to this property. So when we access this property using student object and convert it into string format, then it throws null exception as shown below.For Example:

     

    using System;
    
    
    namespace StringConsoleApplication
    {
        class Program
        {
            static void Main(string[] args)
            {
                Student student = null;
                Console.WriteLine(student.ToString());
            }
        }
    
        public class Student
        {
            public string Name { get; set; }
        }
    }

     

    See the below mentioned screenshot for reference:

     

     

     

    To resolve this issue .Net provides us Convert.ToString() which is the inbuilt method in .net framework. Convert.ToString() will return an empty string  when you access a property with its object with no value that means if the object is NULL then it will not throw the exception, it will return the empty string and program can be successfully executed.

     

    using System;
    
    namespace StringConsoleApplication
    {
        class Program
        {
            static void Main(string[] args)
            {
                Student student = null;
                Console.WriteLine(Convert.ToString(student));
                Console.ReadLine();
            }
        }
    
        public class Student
        {
            public string Name { get; set; }
        }
    }
    

     

    So according to the architecture you design you can choose one over other.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: