Restricted to the specific error of the question, what is missing is a conversion from class DateTime
result of Convert.ToDateTime()
to class DateTime?
.
But I advise you to treat it further, it's not just because the string is not empty that it has a value that can be converted to DateTime
.
See:
string data_string = "teste";
DateTime data_parsed;
DateTime? data = DateTime.TryParse(data_string, out data_parsed) ? (DateTime?)data_parsed : null;
This way data
is still null
and your routine will continue without any problems.
If you do as you suggested in your answer, if the conversion is unsuccessful, 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 is
an unknown word that begins 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 would hardly happen in without program for other validations and restrictions of entry. But in more complex architectures, generalizations and decoupling this could come to 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.