CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Eric Wise

Business & .NET

Convert.ToString vs ToString()

What's the difference? Here's a console application that shows one:

        Dim myObject As Object = Nothing
        Dim toStringTest As String
        Dim convertTest As String

        Try
            toStringTest = myObject.ToString()
        Catch ex As Exception
            Console.WriteLine("MyObject.ToString Error: " & ex.Message)
        End Try

        Try
            convertTest = Convert.ToString(myObject)
        Catch ex As Exception
            Console.WriteLine("Convert.ToString(MyObject) Error: " & ex.Message)
        End Try

        If TypeOf toStringTest Is String Then
            Console.WriteLine("toStringTest is a string!")
        Else
            Console.WriteLine("toStringTest is NOT a string!")
        End If

        Try
            If TypeOf (toStringTest.ToString()) Is String Then
                Console.WriteLine("toStringTest.ToString() is a string!")
            Else
                Console.WriteLine("toStringTest.ToString() is NOT a string!")
            End If
        Catch ex As Exception
            Console.WriteLine("toStringtext.ToString() Error: " & ex.Message)
        End Try

        Try
            If TypeOf convertTest Is String Then
                Console.WriteLine("convertTest is a string!")
            Else
                Console.WriteLine("convertTest is NOT a string!")
            End If
        Catch ex As Exception
            Console.WriteLine("convertTest.ToString() Error: " & ex.Message)
        End Try

Output:

MyObject.ToString Error: Object reference not set to an instance of an object.


toStringTest is NOT a string!


toStringtest.ToString() Error: Object reference not set to an instance of an object.


convertTest is a string!



Comments

John Papa said:

Very intereString. (sorry, couldn't resist)
# April 7, 2005 8:05 AM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add
Check out Devlicio.us!