How to Type Cast null as Bool in C#?
Asked Answered
C

3

19

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;
Crosier answered 4/1, 2016 at 5:48 Comment(1)
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.Almanza
G
41

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;
Gothart answered 4/1, 2016 at 5:50 Comment(1)
I'd use the alternative one primarily .. :)Jeffersonjeffery
M
0

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

        var x = (bool?) null;
        var y = x == true;
Marmion answered 6/1, 2022 at 10:55 Comment(0)
S
-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

Suellen answered 4/1, 2016 at 5:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.