vendredi 21 septembre 2018

Why .NET executes code on false IF statement?

I have following code:

var dateFrom = DateTime.Parse(string.Format(string.Format("01.04.{0}", dateProperty.Value.AddYears(-1).Year))
if (object.nullablebool.HasValue ? object.nullablebool.Value : false  
&& (string == "V" || string == "N")
&& someDate.HasValue && object.SomeOtherDate.HasValue 
&& someDate.Value.Date > dateFrom.Date)
{
       >> Code
}

I have tested adding .Date or even specifiing exact year from the DateTime struct, but nothing worked.

When executing the code, even if

someDate.Value.Date > dateFrom.Date

equals 1700 > 2018, the code executed as if it was true, even though the debugger says it´s false.

When I removed this part from the condition, following code:

someDate.HasValue && object.SomeOtherDate.HasValue

When I made someDate null, so someDate.HasValue is false, the if statement still executes as true.

What did it fix? Taking these two conditions to another if:

var dateFrom = DateTime.Parse(string.Format(string.Format("01.04.{0}", dateProperty.Value.AddYears(-1).Year))
if (object.nullablebool.HasValue ? object.nullablebool.Value : false  
&& (string == "V" || string == "N"))    
{
     if (someDate.HasValue && object.SomeOtherDate.HasValue 
     && someDate.Value.Date > dateFrom.Date)
     {
          >> Code
     }
     else 
     {
          >> Code 
     }           
}

The code works, but it´s way too ugly. I'm running on Visual Studio 2017 Pro. Any ideas why it behaves like that? Executing false statements? Thanks

Aucun commentaire:

Enregistrer un commentaire