When using the If operator (http://msdn.microsoft.com/en-us/library/bb513985(v=VS.100).aspx) to assign a value to a System.Nullable object, if the result is Nothing (null), then 0 is assigned to the object.
Example:
'Expected value is null (Nothing). Actual value assigned is 0.
Dim x As System.Nullable(Of Integer) = If(1 = 0, 1, Nothing)
If x is a nullable type, why is it being assigned the default integer type of 0. Shouldn't it receive a value of null?
Nothing in the context of a value type resolves to the default value for that type. For an integer, this is just 0.
The If operator does not do any conversions between its argument types, they are all treated equally – as Integer in your case. Hence your code is the same as
Dim x As Integer? = If(1 = 0, 1, 0)
To make the result nullable, you need to make the types explicit.
Dim x As Integer? = If(1 = 0, 1, CType(Nothing, Integer?))
Rather than return Nothing cast as Integer? Just create a new Integer? and return it.
Also, keep in mind when working with Nullable types, you should always use the .Value, .HasValue and .GetValueOrDefault methods on Nullable(Of T) rather than just returning the object. Thus in your case, the Value of X is indeed 0, but if you check the HasValue property it should return False to indicate the null situation. Similarly, if you want to check If x = Nothing, it will return False, but If x.HasValue = False returns True.
You could also write your example as follows which works correctly:
Dim x as Integer? = If(1=0, 1, new Integer?)
Console.WriteLine(x)
Console.WriteLine(x.HasValue)
Outputs: null False
来源:https://stackoverflow.com/questions/7245989/assigning-result-of-if-operator-to-system-nullable-type