dim val1 As Integer? = If(5 > 2, Nothing, 43)
' val1 = 0
dim val1 As Integer? = If(5 > 2, Nothing, Nothing)
' val1 = Nothing
What gives? Is this a bug, or am I overlooking something?
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.
The problem is that
Nothingin VB.NET works differently than, for example,nullin C#. WhenNothingis used in the context of a value type (such asInteger) it represents the default value of that type. In this case, that’s 0.In your first example, both branches of the ternary operator are valid
Integervalues. The true branch represents 0 and the false branch represents 43.In the second example, neither branch of the ternary operator is a valid
Integervalue, thus forcing the VB.NET compiler to assume that the overall operator returnsObject, notInteger.To make the first example work the way you intend, you need to make it clear to the compiler that the ternary operator should resolve to an
Integer?, not anIntegeror anObject. You can do so like this:By explicitly making the false branch of the operator an
Integer?, theNothingin the true branch will represent the null value, instead of the defaultIntegervalue.