Thursday, 15 January 2015

vb.net - wrong result with IF() function and a nullable integer? -


I hope to return the value of the nothing to the following vb.net function, but its Instead of 0 ...

  is returning a value of the public share function GetDefaultTipoSrvTkt () as an integer? GetDefaultTipoSrvTkt = (integer, DataRow) as the slow-tsrvDict New Dictionary if (IsNothing (tsrvDict) OrElse tsrvDict.Count = 0, nothing, tsrvDict.First.Key) expiration function  
< P> The last line's function can also be written as a return (IsNothing (tsrvDict) OrElse tsrvDict.Count = 0, nothing, tsrvDict.First.Key) but in any case , Why is () function if (IsNothing (tsrvDict) OrElse tsrvDict.Count = 0, nothing, tsrvDict.First.Key) return 0 < / Code> rather than nothing ?

is nothing to be applied as a value type in VB The context type, and in all cases, means "the default value of this type", for example:

  dim x integer = nothing Console.WriteLine (x) For the '0  

if () operator, VB has to detect the return type in some way, it sees both branches, and Their l A shows the nearest common type. In this case, there is a branch type integer second nothing , which is "typeless", but it is compatible with integer As we saw earlier Therefore, the result of type is integer being predicted. When is nothing given in that context, it becomes 0

A clear cast will correct:.

  GetDefaultTipoSrvTkt = if (_IsNothing (TsrvDict) OrElse tsrvDict.Count = 0, _ CType (nothing, integer?), _ TsrvDict.First.Key)  

Or you can use an alternative method to specify zero value for Nullable type:

  GetDefaultTipoSrvTkt = if (_Is nothing (tsrvDict) OrElse tsrvDict.Count = 0, _ New Integer? (), _ TsrvDict.First.Key)  

No comments:

Post a Comment