How to use Conditional Operation with Nullable Int

前端 未结 5 1407
一生所求
一生所求 2021-02-15 12:38

A small problem. Any idea guys why this does not work?

int? nullableIntVal = (this.Policy == null) ? null : 1;

I am trying to return null

5条回答
  •  再見小時候
    2021-02-15 13:14

    This works: int? nullableIntVal = (this.Policy == null) ? null : (int?)1;.

    Reason (copied from comment):

    The error message is because the two branches of the ?: operator (null and 1) don't have a compatible type. The branches of the new solution (using null and (int?)1) do.

提交回复
热议问题