7

In my class I have these setters/getters:

public int Id { get; set; }
public String ProjectName { get; set; }
public String ProjectType { get; set; }
public String Description { get; set; }
public String Status { get; set; }
public DateTime StartDate { get; set; }

DateTime is a non-nullable type. So, when I retrieve my data from my legacy database that I pass to the class constructor, I get an error when the StartDate is null.

How should I go about designing around this?

Thanks Eric

1 Answers1

14

You can make any struct nullable starting with .NET 2.0.

 public DateTime? StartDate { get; set; }

Notice the ?. Its a compiler operator to make Nullable<DateTime>.

When pulling it out of the reader, you can do this

 obj.StartDate = reader["StartDate"] as DateTime?;

Here is some more information on nullable types: http://www.codeproject.com/Articles/275471/Nullable-Types-in-Csharp-Net

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • @NominSim No you do. `DateTime` is a value type. – Daniel A. White Jul 11 '12 at 13:29
  • @DanielA.White [`Nullable` is also a value type](http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx), but must have some special gubbins going on to be used with `as` like that, likely the same gubbins that allow you to assign `null` to it. – Adam Houldsworth Jul 11 '12 at 13:33
  • @AdamHouldsworth - true. the compiler knows a lot about this type. – Daniel A. White Jul 11 '12 at 13:33
  • @AdamHouldsworth Nullable is a nullable value type, whereas DateTime is a non-nullable value type. Therein lies the difference. – NominSim Jul 11 '12 at 13:34
  • @NominSim That's a bit too "chicken and egg" for me :-) But I was more making reference to the fact that `as` only works with reference types by design, but `Nullable` must have special case handling to work. – Adam Houldsworth Jul 11 '12 at 13:35