I know the title might look little vague but I couldn't come up with something better. So my question is that in my company they are paying close attention to String conversion functions.
And so far I've been dealing with CStr()
, Convert.ToString()
and ToString()
and I need to understand what the difference 开发者_JS百科is between these functions.
They said they were preferring the CStr()
and Convert.ToString()
and I would like to know why they decided to go with these two?
Is it because ToString()
depends on the object?
Here's a bit of code that demonstrates string conversions with each method on three types of data: string, numeric and null reference. Note that only the instance.ToString call will throw an exception if the object has not been initialized.
imports System
public module MyModule
Sub Main()
Dim nothingObj as Object ' leave uninitialized on purpose
Console.WriteLine(Convert.ToString("hello Convert.ToString"))
Console.WriteLine(Convert.ToString(22))
Console.WriteLine(Convert.ToString(nothingObj))
Console.WriteLine(CStr("hello CStr"))
Console.WriteLine(CStr(23))
Console.WriteLine(CStr(nothingObj))
Console.WriteLine("hello .ToString".ToString())
Console.WriteLine(24.ToString())
try
Console.WriteLine(nothingObj.ToString())
catch
Console.WriteLine(CStr("tried ToString on null!"))
end try
Console.ReadKey()
End Sub
end module
Output:
hello Convert.ToString
22
hello CStr
23
hello .ToString
24
tried ToString on null!
I put this little demo together in Snippet Compiler. If you don't have it yet, get it. It's perfect for tweaking with little concepts like this.
I believe it's because of the failure differences, CStr and Convert.ToString() don't throw an exception and return a default known value; .ToString() can throw an exception.
Theoretically, either way is ok; you can catch an exception around .ToString() and it's not a performance overhead because exception handling only incurs a cost if it's used.
But to developers from a VB/ASP background the known default failure path is more familiar and comfortable.
Nowadays, it's a style choice really.
Edit: In other words, .ToString does depend on the object, if the object is null then it has to throw an exception. Convert.ToString() would test the object to make sure it's not null and can behave differently.
精彩评论