Using nullable types in Linq expressions

var quantSubset =
    from userAns in userAnalysis.AllUserAnswers
    join ques in userAnalysis.AllSeenQuestions on userAns.QID equals ques.QID
    where (ques.QuestionType == "QT")
    select new {
        QuestionLevel = ques.LevelID,
        TimeTaken = userAns.TimeTaken,
        Points = userAns.Points,
        UsedWeapon = (userAns.UsedBy2 && userAns.UsedHint),
        WasCorrect = userAns.WasCorrect.HasValue ? userAns.WasCorrect.Value : null
    };

In my select expression I want to select a nullable type WasCorrect (last part of the expression) but apparently I cannot do it the way I am currently trying.

How can I get WasCorrect as nullable type

I tried ?WasCorrect but that also doesnt gives error in Visual Studio.


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