I am wondering which is more efficient, using CStr()
or object.toString()
.
The reason I ask this is because I thought all that CStr() does is to invoke the .ToString() method on the object it was dealing with.
But when recently using a generic method without any type constraints I had to use object.ToString() instead of CStr(object).
The following is purely an example to illustrate the issue.
Public Function IDFromObject(Of ID_TYPE)(ByVal value As ID_TYPE) As String
Return value.ToString
End Function
Compiled as expected, but the following did not using CStr(). It gave an compilation error value of type ID_TYPE cannot be converted to string. But it obviously can use .ToString()
Public Function IDFromObject(Of ID_TYPE)(ByVal value As ID_TYPE) As String
Return CStr(value)
End Function
From here (couldn't say it any better):
CStr is a keyword, whereas ToString is a function (method). CStr is compiled inline and it creates code depending on the type of the passed object. It's mainly there for people being used to it from previous VB versions. I haven't used CStr in .Net anymore (because it's not obvious what it does in which situations and it's also not very well documented).
The difference depends on which ToString function you use. Every type can have it's own implementation.