18

I'm having one null-able bool (bool?) variable, it holds a value null. One more variable of type pure bool, I tried to convert the null-able bool to bool. But I faced an error "Nullable object must have a value."

My C# Code is

bool? x = (bool?) null;
bool y = (bool)x;
B.Balamanigandan
  • 4,713
  • 11
  • 68
  • 130
  • 2
    Your value is `null`...it has no `bool` value to be cast to - if you'd like the default value for the type to be assigned if `x` is null, use the `GetValueOrDefault()` method. – Preston Guillot Jan 04 '16 at 05:51

3 Answers3

40

Use x.GetValueOrDefault() to assign default value (false for System.Boolean) to y in the event that x.HasValue == false.

Alternatively you can use the null-coalescing operator (??), like so:

bool y = x ?? false;
Kirill Shlenskiy
  • 9,367
  • 27
  • 39
0

Checking for equality with a boolean constant is a convenient shortcut:

        var x = (bool?) null;
        var y = x == true;
pasx
  • 2,718
  • 1
  • 34
  • 26
-1

If I have a property boolean

If (HasData.HasValue) Then
            Dim value As Boolean = HasData.Value
        End If
        ' or you can also do this
        If (HasData IsNot Nothing) Then

    End If

That should fix your bug.

hope this helps

Ghasem
  • 14,455
  • 21
  • 138
  • 171