C# Nullable in conditional statement [duplicate]

隐身守侯 提交于 2019-12-10 18:39:50

问题


Why do we need explicit cast in second statement?

bool? a = null; bool b = false; bool c = true;

1.) if(b || c) a = b; else a = null;

2.) a = (b || c)?(Nullable<bool>)b:null;


回答1:


The conditional operator is an expression, thus it needs a return type - also both cases have to have the same return type. In your case, there is no way of determining the return type automatically, thus you need to cast.




回答2:


To add to Femaref, equivalent "if" code will be something like

private static bool? Assign(bool b, bool c)
    {
        if (b || c)
        {
            return b;
        }
        else return null;
    }
...

a = Assign (b,c)

Note the bool? return type. This is what's happening in the conditional operator statement



来源:https://stackoverflow.com/questions/5707889/c-sharp-nullable-in-conditional-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!