GaryJustGary
GaryJustGary

Reputation: 23

Implicit conversion from Boolean? to Boolean

I'm getting a few Implicit Conversion warnings and I cannot for the life of me figure out what is wrong. I think I'm having a mental block.

An example of where I am seeing the implicit conversion from Boolean? to Boolean is as follows:

If Not calId Is Nothing Then
   Dim calendar As Model.Calendar = db.Calendars.First(Function(x) calId = x.id)
End If

Any help would be much appreciated.

Upvotes: 0

Views: 1441

Answers (1)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112482

Use callId.Value. If callId is Integer?, then callId.Value is Integer. Because callId is nullable, the expression callId = x.id becomes a nullable Boolean, i.e. Boolean?. Since you need a non-nullable Boolean expression, write

Dim calendar As Model.Calendar = db.Calendars.First(Function(x) calId.Value = x.id)

Note that the null test can also be written as

If calId.HasValue Then

The reason for this behavoir is that Nothing = x.id yields Nothing, not False.


Note also that calender is limited to the scope of the Then-block. If you need to use it after the If-statement, place the Dim-statement before If

Dim calendar As Model.Calendar = Nothing
If calId.HasValue Then
    calendar = db.Calendars.First(Function(x) calId.Value = x.id)
End If
Console.WriteLine(calender?.Date)

Upvotes: 3

Related Questions