Possible Duplicate:
Bug?? If you assign a value to a nullable integer via a ternary operator, it can't become null
While this question may seem like a duplicate of many, it is actually being asked for a specific reason. Take this code, for example:
Dim n As Integer? = If(True, Nothing, 1)
In that code, the ternary expression should be returning Nothing, but it’s setting n to 0. If this were C#, I could say default(int?) and it would work perfectly. Now it looks like I am going to have to ditch the ternary and use a regular If block, but I really want to use the ternary.
If Nothing were truly VB.NET’s equivalent to C#’s default, how can you explain this behavior?
The VB.NET equivalent to C#’s
defaultis the keywordNothing. The code you wrote should compile just fine so long asId.Valuereturns anIntegervalue.The reason your updated sample is going wrong is because of the nature of
Nothing. In VB.NETNothingis the empty value and it’s convertible to any type. Now for anIfexpression, the compiler has to infer what the type of the return should be, and it does this by looking at the two value arguments.The value
Nothinghas no type, but the literal1has the typeInteger.Nothingis convertible toIntegerso the compiler determinesIntegeris the best type here. This means whenNothingis chosen as the value, it will be interpreted asIntegerand notInteger?.The easiest way to fix this is to explicitly tell the compiler that you want
1to be treated as anInteger?.