vb.net Boolean and Nothing

Arthur Rey picture Arthur Rey · Nov 12, 2013 · Viewed 22.8k times · Source

Let's define this function :

Public Function Test(ByVal value As Boolean)
    Return "blabla" + If(value = Nothing, "", If(value, "1", "0"))
End Function

I want it to do the following : Test(True) -> "blabla1", Test(False) -> "blabla0", Test(Nothing) -> "blabla".

Problem is that Test(Nothing) returns "blabla0".

Answer

Guffa picture Guffa · Nov 12, 2013

A Boolean value can never be null (Nothing), the values that are possible are True and False. You need a nullable value, a Boolean?, for it to be able to be null.

Use the HasValue and Value properties of the nullable value to check if there is a value, and get the value:

Public Function Test(ByVal value As Boolean?)
  Return "blabla" + If(Not value.HasValue, "", If(value.Value, "1", "0"))
End Function