I was writing to some code where I needed to read the date value from a Calendar control in my page (Ajax toolkit: calendar extender).
The code below:
var Endtime = DateTime.Now();
DateTime startTime = item.REPORT_TIME.HasValue ? item.REPORT_TIME.Value : Endtime;
Means: the type of item.item.REPORT_TIME is system.DateTime?
howerver the type of startTime is system.DateTime;
so the code can changed it like
`var Endtime=DateTime.Now; var startTime=item.REPORT_TIME.HasValue?Convert.ToDateTime(item.REPORT_TIME.HasValue):Endtime
`
DateTime?
is the same as Nullable<DateTime>
That is: an instance of DateTime?
can contain 'NULL', whereas an instance of DateTime
does not.
(This is true for all value - types since .NET 2.0. A Value type cannot contain NULL , but, as from .NET 2.0, nullable value types are supported via the Nullable<T>
construct (or the ? shorthand).
You can get the value of DateTime? and put it in DateTime by doing this:
DateTime? someNullableDate;
DateTime myDate;
if( someNullableDate.HasValue )
myDate = someNullableDate.Value;
Another, conciser way to get the value of a Nullable, is by using the null-coalescing operator:
DateTime myDate = someNullableDate?? default(DateTime);
You can use the ?? operator to work with nullables in a very concise way in C#. See my comment on Travis's answer for a shorter way of expressing the "if not null then use it else use some default value" concept. They both do the same thing.
The Calendar control returns a Nullable<DateTime> (shorthand in C# is DateTime?) in its SelectedDate Property, since DateTime is a struct. The null value allows the Control to have a "no date selected" state. Thus, you'll need to check if the nullable has a value before you can use it.
var nullable = myCalendarExtender.SelectedDate; var newSelectedDate = (nullable.HasValue) ? nullable.Value : SomeDefaultValue;
EDIT: Even more concise, thanks to Josh's comment:
var newSelectedDate = myCalendarExtender.SelectedDate ?? SomeDefaultValue;
I like it!
A much better solution and IMO the best feature of all with the nullable class
DateTime newSelectedDate = myCalendarExtender.SelectedDate.GetValueOrDefault();
? means that the type is nullable. For details, see e.g. MSDN
Nullable is a compiler-supported wrapper around value types that allows value types to become null.
To access the DateTime value, you need to do the following:
DateTime? dateOrNull = myCalendarExtender.SelectedDate;
if (dateOrNull != null)
{
DateTime newSelectedDate = dateOrNull.Value;
}