This post originated from an RSS feed registered with .NET Buzz
by Eric Wise.
Original Post: Convert.ToString vs ToString()
Feed Title: Eric Wise
Feed URL: /error.htm?aspxerrorpath=/blogs/eric.wise/rss.aspx
Feed Description: Business & .NET
What's the difference? Here's a console application that shows one:
Dim myObject AsObject = Nothing Dim toStringTest AsString Dim convertTest AsString
Try toStringTest = myObject.ToString() Catch ex As Exception Console.WriteLine("MyObject.ToString Error: " & ex.Message) EndTry
Try convertTest = Convert.ToString(myObject) Catch ex As Exception Console.WriteLine("Convert.ToString(MyObject) Error: " & ex.Message) EndTry
IfTypeOf toStringTest IsStringThen Console.WriteLine("toStringTest is a string!") Else Console.WriteLine("toStringTest is NOT a string!") EndIf
Try IfTypeOf (toStringTest.ToString()) IsStringThen Console.WriteLine("toStringTest.ToString() is a string!") Else Console.WriteLine("toStringTest.ToString() is NOT a string!") EndIf Catch ex As Exception Console.WriteLine("toStringtext.ToString() Error: " & ex.Message) EndTry
Try IfTypeOf convertTest IsStringThen Console.WriteLine("convertTest is a string!") Else Console.WriteLine("convertTest is NOT a string!") EndIf Catch ex As Exception Console.WriteLine("convertTest.ToString() Error: " & ex.Message) EndTry
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.