Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.DateTime? vs System.DateTime

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:

DateTime newSelectedDate = myCalendarExtender.SelectedDate; 

gives the following error:

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists (are you missing a cast?) 

However, by inserting a cast I can get the code to work:

DateTime newSelectedDate = (DateTime)myCalendarExtender.SelectedDate; // works fine! 

The 'SelectedDate' property for the calendar control (Ajax toolkit) describes the data type as 'System.DateTime?' ... clearly the '?' has something to do with all of this.

What exactly is happening when a data type contains this symbol (?)... I presumed that I could apply the 'SelectedDate' property straight into a variable of type 'DateTime' without casting.

Thanks

like image 936
Dalbir Singh Avatar asked Nov 13 '09 14:11

Dalbir Singh


People also ask

What is System DateTime now?

The Now property returns a DateTime value that represents the current date and time on the local computer.

What is the difference between DateTime now and DateTime today?

The DateTime. Now property returns the current date and time, for example 2011-07-01 10:09.45310 . The DateTime. Today property returns the current date with the time compnents set to zero, for example 2011-07-01 00:00.00000 .

What is DateTime type in C#?

C# DateTime is a structure of value Type like int, double etc. It is available in System namespace and present in mscorlib. dll assembly. It implements interfaces like IComparable, IFormattable, IConvertible, ISerializable, IComparable, IEquatable.


2 Answers

? 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; } 
like image 55
Marek Avatar answered Sep 24 '22 02:09

Marek


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); 
like image 25
Frederik Gheysels Avatar answered Sep 23 '22 02:09

Frederik Gheysels