Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast from Object to Integer in VB.NET?

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.

like image 324
CJ7 Avatar asked Oct 31 '12 04:10

CJ7


3 Answers

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.

like image 192
Jonathon Reinhart Avatar answered Oct 19 '22 06:10

Jonathon Reinhart


You can use this:

Dim intMyInteger as Integer

Integer.TryParse(MyObject, intMyInteger)
like image 39
CoOl Avatar answered Oct 19 '22 07:10

CoOl


Use Directcast and catch InvalidCastException

like image 28
Swordblaster Avatar answered Oct 19 '22 06:10

Swordblaster