Home > .net 3.5, LINQ, Visual Studio 2008 > Reminder: Handling Nullable Types in LINQ

Reminder: Handling Nullable Types in LINQ

July 18, 2007

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.



  1. April 1, 2009 at 6:02 pm

    Won’t using just .Value throw an exception if the value is null?

    I’ve always had the need to check the nullable instance with .HasValue before accessing .Value, otherwise i’d get an excpetion if the instace had no value.

    I found your site searching for this detail. I’m trying to implement a sort based on a nullable property (using Linq which I am very inexperienced at using), and the nullable type has no CompareTo method, and i’m worried that if the list has an item with a null value, that the sort will throw when checking .Value directly.. outta try this on a test porject…

  1. No trackbacks yet.
Comments are closed.
%d bloggers like this: