How should I cast from an Object
to an Integer
in VB.NET?
When I do:
Dim intMyInteger as Integer = TryCast(MyObject, Integer)
it says:
TryCast operand must be reference type, but Integer is a value type.
TryCast
is the equivalent of C#'s as
operator. It is a "safe cast" operator that doesn't throw an exception if the cast fails. Instead, it returns Nothing
(null
in C#). The problem is, you can't assign Nothing
(null
) (a reference type) to an Integer
(a value type). There is no such thing as an Integer
null
/Nothing
.
Instead, you can use TypeOf
and Is
:
If TypeOf MyObject Is Integer Then
intMyInteger = DirectCast(MyObject, Integer)
Else
intMyInteger = 0
End If
This tests to see if the runtime type of MyObject
is Integer
. See the MSDN documentation on the TypeOf
operator for more details.
You could also write it like this:
Dim myInt As Integer = If(TypeOf myObj Is Integer, DirectCast(myObj,Integer), 0)
Furthermore, if an integer with a default value (like 0) is not suitable, you could consider a Nullable(Of Integer)
type.
You can use this:
Dim intMyInteger as Integer
Integer.TryParse(MyObject, intMyInteger)
Use Directcast and catch InvalidCastException
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