0

I am trying to set the date time to an empty value in my application - I am trying in the following way

    string datetime = Convert.ToString(dataRow["dbfield"]).Trim();
    MyDateTime= string.IsNullOrEmpty(datetime)
                    ? (DateTime?) null
                    : GeneralUtilities.ConvertOTDateToDate(datetime);

The error I am getting is

cannot implicitly convert type System.Datetime? to System.Datetime, an explicit conversion exists are you missing a cast?

Please could someone help me with the correct syntax required for this please?

Thanks

3 Answers 3

4

I assume MyDateTime is declared as a DateTime. Change it to DateTime?.

or

GeneralUtilities.ConvertOTDateToDate returns a DateTime. Cast it to DateTime?. As in:

MyDateTime= string.IsNullOrEmpty(datetime)
                ? (DateTime?) null
                : (DateTime?)GeneralUtilities.ConvertOTDateToDate(datetime);
Sign up to request clarification or add additional context in comments.

5 Comments

second one is true, he's returning two different values
@wudzik No it's definitely the first one because you can implicitly convert DateTime to DateTime?.
@cFrozenDeath: It is, but that's not related to OPs issue. @juharr, it's hard to judge which it is, since the declaration of MyDateTime isn't provided, nor is the method signature to GeneralUtilities.ConvertOTDateToDate
@Amy, The message is about converting a DateTime? to a DateTime. The result of the ternary operator will be a DateTime? becuase of the cast regardless of what the method returns. Thus the variable is DateTime.
@cFrozenDeath The cast is only redundant if the method returns DateTime? if it returns DateTime then the cast will force the ternary return to be DateTime?.
2

DateTime is a struct and thus cannot be null. Change it to a DateTime? if you want to use null. Alternatively use something like DateTime.MinValue as the default value.

Comments

0

GeneralUtilities.ConvertOTDateToDate must return a nullable DateTime instead of a normal DateTime, probably.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.