Compiler Error for Nullable Bool

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

Its generating exception .

Cannot implicitly con

5条回答
  •  长情又很酷
    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";
    

提交回复
热议问题