Trying to get to the bottom of a little mystery.
I have the following If Statement:
Dim myVal As Nullable(Of Guid)
myVal = If(vendor.Address.ID = Guid.Empty, Nothing, vendor.Address.ID)
The end value of myVal
here is, inexplicably, Guid.Empty
.
If I write that same code as follows:
Dim myVal As Nullable(Of Guid)
If(vendor.Address.ID = Guid.Empty) Then
myVal = Nothing
Else
myVal = vendor.Address.ID
End If
Why the difference?
The problem is in how VB.NET infers types using the If
operator. Both operands must be the same type. Given Nothing
on one side and a Guid
on the other, it assumes the result type should be a Guid
, so it coerces the Nothing
to Guid.Empty
. Putting an explicit cast to Nullable(Of Guid)
on either side will be enough tell the compiler that that's what you really want.
This should give you the results you expect:
Dim myVal2 As Nullable(Of Guid)
myVal2 = If(vendor.Address.ID = Guid.Empty, CType(Nothing, Nullable(Of Guid)), vendor.Address.ID)
Or this:
Dim myVal2 As Nullable(Of Guid)
myVal2 = If(vendor.Address.ID = Guid.Empty, Nothing, CType(vendor.Address.ID, Nullable(Of Guid)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With