user290043
user290043

Reputation:

How to design class around null values from database?

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

Upvotes: 7

Views: 193

Answers (1)

Daniel A. White
Daniel A. White

Reputation: 190942

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

Upvotes: 14

Related Questions