Kevin Meredith
Kevin Meredith

Reputation: 41909

Nullable for ORM Objects

Based on reading Nullable Types, I understand that it's proper to use Nullable for a primitive type that may be null in a database.

Is it necessary to use the ? (Nullable) type for objects?

Example:

public DateTime? DateCreated {get; set; }

or

 public DateTime DateCreated {get; set; }

Upvotes: 0

Views: 125

Answers (2)

Yannis
Yannis

Reputation: 6157

Your example is correct. You will need DateTime? to have the ORM (say NH) treat it as a nullable type. For objects you dont need to put the question mark.

Also, on a side-note, the question mark T? is an alias for Nullable<T>. The compiler will translate the T? to Nullable<T>. You can check this on the debugger if you want a proof :)

Upvotes: 1

wgraham
wgraham

Reputation: 1393

In your example, Nullable<T> is valid as DateTime is not a reference type. However, for objects (and types derived from object), you cannot use Nullable<T> as the compiler will throw an error; see: C# nullable string error

Upvotes: 0

Related Questions