Compiler Error for Nullable Bool

前端 未结 5 1179
一向
一向 2021-01-19 07:45
 bool? ispurchased = null;
    var pospurcahsed= ispurchased ? \"1\":\"2\";

Its generating exception .

Cannot implicitly con

相关标签:
5条回答
  • 2021-01-19 08:26

    You should use .value

    bool? ispurchased = null;
    
    if (ispurchased.HasValue)
    {
        var pospurcahsed = ispurchased.Value ? "1" : "2";
    }
    
    0 讨论(0)
  • 2021-01-19 08:28

    This is not allows because it is unclear what null means in the context of a conditional.

    Nullable Booleans can be cast to a bool explicitly in order to be used in a conditional, but if the object has a value if null, InvalidOperationException will be thrown.

    It is therefore important to check the HasValue property before casting to bool.

    Use like

       var pospurcahsed=  (ispurchased.HasValue && ispurchased.Value) ?......
    

    Nullable Booleans are similar to the Boolean variable type used in SQL. To ensure that the results produced by the & and | operators are consistent with SQL's three-valued Boolean type, the following predefined operators are provided:

    bool? operator &(bool? x, bool? y)
    
    bool? operator |(bool? x, bool? y)
    

    enter image description here

    or you can use martin suggestion GetValueOrDefault[Thanks to martin to pointing it out ]

    The GetValueOrDefault method returns a value even if the HasValue property is false (unlike the Value property, which throws an exception).

    0 讨论(0)
  • 2021-01-19 08:29

    You can't use Nullable<bool> or bool? in condition directly, instead use it like:

    var pospurcahsed= (ispurchased.HasValue && ispurchased.Value) ? "1":"2";
    
    0 讨论(0)
  • 2021-01-19 08:32

    You can use something like this

     bool? chk = false; 
    
     //or
    
     bool? chk2 = false;
    
     var test = (chk != null && (bool)chk) ? "1": "2";
    
     //or
    
     var test2 = (chk2.HasValue && (bool)chk2) ? "1" : "2";
    

    I would suggest don't use var keyword for known types.

    Instead of this use Like this:

    String test = (chk != null && (bool)chk) ? "1" : "2";
    
    0 讨论(0)
  • 2021-01-19 08:33

    The issue you have is that the conditional operator ? : expects a bool, not a bool?. You could just cast it and be done, but you'd get an InvalidOperationException if the value contained a null, so you should probably check for that first.

    Given the name of your variable, I've gone ahead and assumed you'd want to treat a null as you would false, so in the code below I check to ensure it has a value, and if it does then it'll use it in the condition. In the event it doesn't have a value (i.e. it's null then the cast will never happen and you won't get the error (the expression would evaluate to false).

    bool? ispurchased = null;
    var pospurcahsed = (ispurchased.HasValue && (bool)ispurchased) ? "1":"2";
    
    0 讨论(0)
提交回复
热议问题