How to design class around null values from database?
Asked Answered
C

1

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

Coheir answered 11/7, 2012 at 13:23 Comment(0)
N
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

Nectarous answered 11/7, 2012 at 13:24 Comment(5)
@NominSim No you do. DateTime is a value type.Nectarous
@DanielA.White Nullable<T> is also a value type, 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.Ethridge
@AdamHouldsworth - true. the compiler knows a lot about this type.Nectarous
@AdamHouldsworth Nullable<T> is a nullable value type, whereas DateTime is a non-nullable value type. Therein lies the difference.Immethodical
@Immethodical 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<T> must have special case handling to work.Ethridge

© 2022 - 2024 — McMap. All rights reserved.