user5252179
user5252179

Reputation: 133

How to use datetime function on null value string without throwing any exception

I have been using C# for trying to parse a string into datetime format. It works as long as the string is not null but fails when its null. I used datetime.parse but it failed:

Datetime.parse:

 Datetime ContactDate =   DateTime.Parse((GetContactDateForClient(1)?.DisplayText))  -- (note: getcontactdateforclient.displaytext is one of my method which gets back date in string format)

Whenever my method gets back date as non null the above works great but if its null then my above line of code fails. I tried datetime.tryparse but it shows me error during compilation ("Cannot convert System.Datetime ? to System.Datetime")
Datetime.TryParse:

        DateTime value;
        Datetime ContactDate = DateTime.TryParse((GetContactDateForClient(1)?.DisplayText), out value)  ? value: (DateTime?) null;

Is it possible to assign 'ContactDate' value as null if the string is null and if not null then get the value as it comes back(GetContactDateForClient(1)?.DisplayText). Any pointer much appreciated.

Upvotes: 0

Views: 1899

Answers (3)

Yurii N.
Yurii N.

Reputation: 5703

You can try:

Datetime ContactDate =   DateTime.Parse((GetContactDateForClient(1)?.DisplayText ?? "your default value"))

Upvotes: 1

David
David

Reputation: 218960

Is it possible to assign 'ContactDate' value as null

Sure, just make it a nullable type:

Datetime? ContactDate = DateTime.TryParse(...

That's what the original error was telling you:

"Cannot convert System.Datetime? to System.Datetime"

You were trying to assign a DateTime? (nullable DateTime) to a DateTime. They're different types. Just use the same consistent type.

Upvotes: 1

Krishna
Krishna

Reputation: 1985

You need to declare a nullable datetime

try this

Datetime? ContactDate = DateTime.TryParse((GetContactDateForClient(1)?.DisplayText), out value)  ? value: (DateTime?) null;

Upvotes: 2

Related Questions