Conditional expression type cannot be determined because there is no implicit conversion between "<null>" and "Datetime"

Asked

Viewed 489 times

2

Follows code:

string data_string = "17/01/2018";
DateTime? data = data_string == string.Empty ? null : Convert.ToDateTime(data_string);

I get error:

CS0173 error Conditional expression type cannot be determined because there is no implicit conversion between "null" and "Datetime"

1 answer

2


Restricted to the question specific error what is missing is a class conversion DateTime result of Convert.ToDateTime() for the class DateTime?.

But I advise a further treatment, it is not just because the string is not empty that it has a value that can be converted to DateTime.

Behold:

string data_string = "teste";
DateTime data_parsed;
DateTime? data = DateTime.TryParse(data_string, out data_parsed) ? (DateTime?)data_parsed : null;

Thus data is still null and your routine will proceed without further trouble.

If you do as you suggested in your reply, if the conversion does not succeed, you will receive an error.

string data_string = "Dezessete de Janeiro de Dois Mil e Dezoito";
DateTime? data = data_string == string.Empty ? null : (DateTime?)Convert.ToDateTime(data_string);

The string was not recognized as a valid Datetime. There an unknown word starting at index 0. + System.DateTimeParse.Parse(string, System.Globalization.Datetimeformatinfo, System.Globalization.Datetimestyles) + System.Convert.Todatetime(string)

Of course I used an absurd example and it would hardly happen in without program by other validations and entry restrictions. But on more complex architectures, generalizations and decoupling this could give some headache.

So it’s good to pay more attention to detail, the solution is not always the answer and never trust your input data.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.