Reminder: Handling Nullable Types in LINQ
I came across this the other day and it took a minute to click exactly what was happening… and the multitude of odd casts I had been trying didn’t help.
So, imagine your database table having a DateTime, Int, or other value in it that you want to return to an object. In SQL, you’d most likely handle a null as a empty value or “” inside your code.
MyTextBox.Text = myRecordObject.RecordDate.ToShortDateString();
However, what if it’s nullable? With LINQ, if you’ve set your fields to allow nulls, that’s exactly what you have. DateTime?, int?, etc. With strings, it’s not a problem, the ToString() method handles it. But with, for example, DateTime types, you can’t run ToShortDateString() against a nullable DateTime. The method doesn’t exist.
You have to remember to run the method against the .Value of the nullable type.
MyTextBox.Text = myRecordFromLinq.RecordDate.Value.ToShortDateString();
I’ll be honest that I haven’t dinked a lot with nullables (though I should rather than manually handling them), so it took a minute for it to click what it was really returning back to me. The property and concept make perfect sense, it just required me to beat my head against the desk a few times to type the . and see what was available.