wrong result with IF() function and a nullable integer?
vb.net
Solution
`Nothing` in VB can be applied to value types as well as reference types, and in all cases means "default value of this type". So, for example:
Dim x As Integer = Nothing
Console.WriteLine(x) ' 0
For `If()` operator, VB has to deduce the return type somehow. It looks at both branches, and figures out the nearest common type for them. In this case, one branch is of type `Integer`. Another is `Nothing`, which is "typeless", but it is compatible with `Integer`, as we saw earlier. Therefore, the result type of `If()` is deduced to be `Integer`. When `Nothing` is returned in that context, it becomes 0.
An explicit cast will fix this:
GetDefaultTipoSrvTkt = If( _
IsNothing(tsrvDict) OrElse tsrvDict.Count = 0, _
CType(Nothing, Integer?), _
tsrvDict.First.Key)
or you can use an alternative way to specify the null value for a nullable type:
GetDefaultTipoSrvTkt = If( _
IsNothing(tsrvDict) OrElse tsrvDict.Count = 0, _
New Integer?(), _
tsrvDict.First.Key)
Problem
I would expect the following vb.net function to return a value of `Nothing`, but instead its returning a value of `0`... ``` Public Shared Function GetDefaultTipoSrvTkt() As Integer? Dim tsrvDict As New Dictionary(Of Integer, DataRow) GetDefaultTipoSrvTkt = If(IsNothing(tsrvDict) OrElse tsrvDict.Count = 0, Nothing, tsrvDict.First.Key) End Function ``` The last line of the function could also be written as `Return If(IsNothing(tsrvDict) OrElse tsrvDict.Count = 0, Nothing, tsrvDict.First.Key)` but in any case, why is the `IF()` function `If(IsNothing(tsrvDict) OrElse tsrvDict.Count = 0, Nothing, tsrvDict.First.Key)` returning `0` instead of `Nothing`?