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
The Now property returns a DateTime value that represents the current date and time on the local computer.
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 .
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.
? 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; }
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With