Tom,
A conversion to string is *always* possible as you simply need to call
Object.ToString!
Instead of:
Dim s As String = CStr(AnyObject)
Use:
Dim s As String = AnyObject.ToString
However converting to a string is not neccessarily the same as getting the
string representation of an object...
For i As Integer = 0 To 5
What the fudge! Is a for loop really necessary to show the example??? IMHO I
really don't think so! :-|
Remember that CStr is short hand for CType(..., String). Remember that CType
is Convert type.
In VS2005 (.NET 2.0) you can overload CType on your own types. If a type has
CType overloaded for String, the CStr will use it.
Decimal is "special" in that VB offers a built-in conversion for it.
TimeSpan is not considered as special so the VB compiler looks for an
overloaded CType method to call.
The "problem" with writing a IsConvertibleToString function is knowing which
types have a built-in conversion & which use an overloaded CType operator...
Also CStr behaves differently when given an object parameter verses a
strongly typed parameter. (which IMHO feels like a bug).
For example:
Public Class Something
' VB 2005 syntax
Public Shared Narrowing Operator CType(ByVal aSomething As
Something) As String
Return aSomething.ToString()
End Operator
End Class
' this statement will fail:
Dim AnyObject As Object = New Something()
' this statement will succeed
Dim AnyObject As New Something()
--
Hope this helps
Jay B. Harlow [MVP - Outlook]
..NET Application Architect, Enthusiast, & Evangelist
T.S. Bradley -
http://www.tsbradley.net
Hi Mattias, thanks for the reply. Cstr() does raise exceptions.
I will explain again my question. Consider the following example:
Dim AnyObject As Object = New TimeSpan(23)
Dim AnyObject2 As Object = 34.5D
For i As Integer = 0 To 5
Try
Dim s As String = CStr(AnyObject)
MsgBox("Conversion1 ok")
Catch ex As Exception
MsgBox("Conversion1 failed")
End Try
Try
Dim s As String = CStr(AnyObject2)
MsgBox("Conversion2 ok")
Catch ex As Exception
MsgBox("Conversion2 failed")
End Try
Next
I would like to find something that let me recognize when a conversion
to string is possible (the object may be anything) without using:
Try
Catch ex As Exception
End Try
This is possible for instance when one want to recognize if something
is convertible to a number :
If IsNumeric(AnyObject) Then
Dim Number As Double = CDbl(AnyObject)
End If
Note that using IsNumeric instead of any Try Catch is highly advisable
and incomparably faster.
My question : what is the corresponing to check id an obj is
convertible to string:
If IsConvertibleoString(AnyObject) Then
Dim Text As String = CStr(AnyObject)
End If
that is : what could the function IsConvertibleoString(AnyObject as
Object) be (clearly, something fast, not using TryCatch) ??
-tom
Mattias Sjögren ha scritto: