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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
TryCastis the equivalent of C#’sasoperator. It is a “safe cast” operator that doesn’t throw an exception if the cast fails. Instead, it returnsNothing(nullin C#). The problem is, you can’t assignNothing(null) (a reference type) to anInteger(a value type). There is no such thing as anIntegernull/Nothing.Instead, you can use
TypeOfandIs:This tests to see if the runtime type of
MyObjectisInteger. See the MSDN documentation on theTypeOfoperator for more details.You could also write it like this:
Furthermore, if an integer with a default value (like 0) is not suitable, you could consider a
Nullable(Of Integer)type.