Using nullable types in Linq expressions

二次信任 提交于 2019-12-05 19:15:21

You need to cast the null value to the nullable type explicitly:

WasCorrect = userAns.WasCorrect.HasValue ?
    userAns.WasCorrect.Value : (TheTypeName?)null

Otherwise C# won’t know which type the conditional expression should be.

Apart from that, the code is completely redundant. You can simply write:

WasCorrect = userAns.WasCorrect

You absolutely must be able to write

select new { WasCorrect = userAns.WasCorrect }

if userAns.WasCorrect is Nullable<bool>.

This code executes without a problem:

class Test {
    public bool? NullableBool { get; set;}
}

class MainClass
{
    public static void Main ()
    {
        Test t1 = new Test { NullableBool = true };
        var a1 = new { NB = t1.NullableBool };

        Test t2 = new Test { NullableBool = null };
        var a2 = new { NB = t2.NullableBool };
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!