tags:

views:

60

answers:

2
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.

+5  A: 

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
Konrad Rudolph
casting `null`? wow, never though we ever needed to do that.
RPM1984
@RPM: You do when the compiler needs to infer the type. e.g., `var val = null; //null what?`
Jeff M
@Konrad Well, I have previously written code just the way you say but whenever it encounters a null value it throws an exception. See details at http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx
sassyboy
@sassyboy: What details should I see on the page you linked? The code I wrote **never** throws an exception. You probably wrote `WasCorrect = userAns.WasCorrect.Value` by mistake instead.
Konrad Rudolph
Something tells me he tried to explicitly cast it to a bool when the value was null. `var b = (bool)x.WasCorrect;` (or whatever type it is)
Jeff M
@konrad ok.. my bad.. a few days ago i had wrote an if condition, if (userAns.WasCorrect) and got an error when a value was null, so after that I have been checking everywhere (userAns.WasCorrect.HasValue). Let me try out what you have pointed out.
sassyboy
Yup it works.. so I guess it works fine with assignment but now on conditional.. makes sense.. thanks all..
sassyboy
+1  A: 

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 };
    }
}
gaearon
@gaearon thanks, Konrad above provided the answer first so I have marked his as answer..
sassyboy
Yes, sure. I only posted this as an answer for the proof code to fit.
gaearon