Search code examples
c#wpfvisual-studio-2010datetimedatetimepicker

Difference between "DateTime?" and "DateTime". (trying to get value from datepicker)


I'm quite new to WPF and C# so don't blame me for asking this maybe silly question.

I have my WPF app with two datepickers. I want to get the DateTime out of them when it changes and to use it as my variable for some other stuff in the app. So I have for each of them something like this(method was automatically generated by VS):

private void datePicker1_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            date1 = datePicker1.SelectedDate;
        }

but the problem is that the date in the datepicker is format DateTime? not DateTime and I really don't know what does that question mark there mean and why it is there. I tried some research but didn't find anything that would help me. If u see some better way of getting the date from that datepicker u can help me with it too. I just need it in my xaml.cs code not in xaml and I'm not really into using bindings cause I'm not sure if it works how I need in this case.

Thanks for any answer.

Edit: I would like to add information that it shows me this error:

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


Solution

  • DateTime with ? is Nullable DateTime, it can hold null values. For your case you can do :

    private void datePicker1_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
    {
        if(datePicker1.SelectedDate.HasValue)
             date1 = datePicker1.SelectedDate.Value;
    }
    

    Nullable<T> C#

    In C# and Visual Basic, you mark a value type as nullable by using the ? notation after the value type. For example, int? in C# or Integer? in Visual Basic declares an integer value type that can be assigned null.