Nullable type and if issue

前端 未结 4 1253
暖寄归人
暖寄归人 2020-12-21 05:08

Here is simplest piece of code

Dim testInvoiceDate As DateTime? = If(String.IsNullOrEmpty(Nothing),
                                      Nothing,
                   


        
4条回答
  •  轮回少年
    2020-12-21 05:51

    It's because you're using the 3-argument form of If(). It will try to return the same type based on parameters 2 and 3, so the Nothing in parameter 2 gets converted to a DateTime (and you get DateTime.MinValue).

    If you use the 2-argument form, it applies null-coalescing, i.e. when the first argument (which must be an Object or a nullable type) is Nothing, it returns the second argument, otherwise it returns the first argument.

    If you use Dim foo As DateTime? = If(Nothing, new DateTime(2018, 3, 20)) you will get the expected value.

提交回复
热议问题