C# - DateTime.TryParse issue - why doesn't it like my string representation of my date?

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

  •  29-06-2022
  •  | 
  •  

Domanda

Here's my code:

            DateTime Dob = Convert.ToDateTime("1/1/1800");
            DateTime Dod = Convert.ToDateTime("1/1/1800");

            if (!DateTime.TryParse(p.birthday, out Dob) && !DateTime.TryParse(p.deathday, out Dod))
            {
                // handle error
            }

p.birthday is:

enter image description here

p.deathday is:

enter image description here

When the .TryParse() code hits, my DateTime object for Dob is:

enter image description here

And the DateTime object for Dod is:

enter image description here

QUESTION: Why is Dod still "1-1-1800" (the initial value I assigned), but Dob is set correctly? Is there something about the Dod value of "2007-02-28" that it doesn't like?

È stato utile?

Soluzione

DateTime.TryParse(p.birthday, out Dob) successfully converts the string to DateTime, so it returns true. You invert this with !, giving false.

When the execution gets to the && operator, it sees the first operand is already false, so doesn't bother executing the second operand.

You could either execute both beforehand, or use the non-shortcut AND operator, &.

Edit: Or

if (!(DateTime.TryParse(p.birthday, out Dob) || DateTime.TryParse(p.deathday, out Dod)))
{
    ...
}

Altri suggerimenti

The reason is that its executing !(DateTime.TryParse(p.birthday, out Dob) and returning false. Therefore !DateTime.TryParse(p.deathday, out Dod) is not executed.

According to

http://msdn.microsoft.com/en-us/library/2a723cdk.aspx

x && y

if x is false, y is not evaluated, because the result of the 
AND operation is false no matter what the value of y is. This is known as 
"short-circuit" evaluation.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top