Bug?? If you assign a value to a nullable integer via a ternary operator, it can't become null

こ雲淡風輕ζ 提交于 2019-12-01 00:26:22

The problem is that Nothing in VB.NET works differently than, for example, null in C#. When Nothing is used in the context of a value type (such as Integer) it represents the default value of that type. In this case, that's 0.

In your first example, both branches of the ternary operator are valid Integer values. The true branch represents 0 and the false branch represents 43.

In the second example, neither branch of the ternary operator is a valid Integer value, thus forcing the VB.NET compiler to assume that the overall operator returns Object, not Integer.

To make the first example work the way you intend, you need to make it clear to the compiler that the ternary operator should resolve to an Integer?, not an Integer or an Object. You can do so like this:

dim val1 As Integer? = If(5 > 2, Nothing, New Integer?(43))

By explicitly making the false branch of the operator an Integer?, the Nothing in the true branch will represent the null value, instead of the default Integer value.

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