On passing a DateTime? variable to a method, compiler says it cannot covert a null value to a DateTime [duplicate]

StackOverflow https://stackoverflow.com/questions/21328150

Question

I have a TextBox control, which is supposed to store a date. As long as the date is not a required field in my page (I'm using Web Forms), I am passing a DateTime? (nullable), not a DateTime variable to a method that connects to the database and inserts the appropriate value. It looks something like this.

public void DatabaseMethod(DateTime? myDate)
{
// Insert the appropriate value into the database
}

// I'm calling the above method like this:
DatabaseMethod(String.IsNullOrWhiteSpace(txtContractMyDate.Text) ? null : Convert.ToDateTime(txtContractMyDate.Text));

I am getting a message from the compiler that goes like "Type of conditional statement cannot be determined because there is no implicit conversion between 'null' and 'System.DateTime'".

I can just do the following:

DateTime? myDate = null;

if (!String.IsNullOrWhiteSpace(txtContractMyDate.Text))
{
    myDate = Convert.ToDateTime(txtContractStornoDate.Text);
}

And then call the method like:

DatabaseMethod(myDate);

And of course, that is okay, but I just can't figure out why I'm getting the stated message from the compiler ("Type of conditional statement cannot be determined because there is no implicit conversion between 'null' and 'System.DateTime'").

Was it helpful?

Solution

You need to cast null to DateTime?

DatabaseMethod(String.IsNullOrWhiteSpace(txtContractMyDate.Text) ? (DateTime?)null : Convert.ToDateTime(txtContractMyDate.Text)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top