Assigning result of If operator to System.Nullable type

℡╲_俬逩灬. 提交于 2019-12-04 12:28:35

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!