Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional statement yields different results then If Then

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?

like image 288
Refracted Paladin Avatar asked Oct 21 '22 05:10

Refracted Paladin


1 Answers

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)))
like image 160
p.s.w.g Avatar answered Oct 27 '22 09:10

p.s.w.g