tags:

views:

133

answers:

4

If I have a query that returns a DateTime, what's the value of FirstOrDefault? Is there a generic way to get the default value of a C# scalar? Example:

var list = (from item in db.Items 
    where item.ID==1234
    select item.StartDate).FirstOrDefault();

Edit: Assume that the column StartDate can't be null.

+1  A: 

Im guessing its default(DateTime) which im guessing (again) is DateTime.MinValue

Jamiec
+2  A: 

default(DateTime) is 1/1/0001 12:00:00 AM.

In your code, the major portion of your query is an IEnumerable of start dates from your database. Your call to FirstOrDefault() is either returning the first element of the enumerable or the default value of its type if there are no elements in the enumerable.

If the type of StartDate is indeed a date and there are no elements in the enumerable, then the result will be the datetime value I provided above.

Anthony Pegram
+10  A: 

The generic way to get a default value for a given generic type is:

default(T)

where T is the generic type parameter in question. For reference types, this will yield null. For value types, this will yield a zero'd instance of the value. For DateTimes, this will be equivalent to DateTime.MinValue.

HTH,
Kent

Kent Boogaart
As a sidenote, you can always "force" a different default using: `collection.DefaultIfEmpty(new DateTime(...)).First();`
Fábio Batista
+1  A: 

DateTime.MinValue

Partha Choudhury