I (obviously incorrectly) had assumed that Cstr(something)
was equivalent to something.ToString
.
I wanted to get hold of an enumerated type as a string and it seems depending on which conversion method I use I either get the index of the enum
or the name:
Public Enum vehicleType
Car
Lorry
Bicycle
End Enum
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MsgBox("Index is " & _
CStr(vehicleType.Car) & _
".Name is " & _
vehicleType.Car.ToString)
End Sub
End Class
Why are these conversions to string returning different elements of the enum
type?
The ToString
method is a standard public method that returns a String
. It is a method that is defined by the base Object
type as overrideable. Each class can, therefore, override that method to return anything that it wants. It is quite common for classes to override the ToString
method to make it return a nice human-readable description of the object.
CStr
, on the other hand, is a casting operator. It is shorthand for CType(x, String)
. The casting operator, like many other operators, can be overridden by any class. Normally, though, you want casting operations to return the closest representation of the actual value of the original object, rather than a descriptive string.
It is not unusual then, that you may want ToString
to return a different result than CStr
. In the case of an enum, each member is essentially an Integer, so CStr
on an enum member works the same as CStr
on an integer. That is what you would expect. However, ToString
has been overridden to return the more human readable version of the value. That is also what you would expect.
Here's an example of a class that overrides both CStr
and ToString
:
Public Class MyClass
Public Overrides Function ToString()
Return "Result from ToString"
End Function
Public Shared Widening Operator CType(ByVal p1 As MyClass) As String
Return "Result from cast to String"
End Operator
End Class
What type of expressions CStr() accepts is explained in detail in this MSDN Library article. Summarizing:
Do note that it doesn't have a bullet for enumerated types. The compiler is always happy to convert an enum value to an integer. So the 3rd bullet applies and this is why you get "0".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With