Search code examples
c#if-statementsimplification

Need help simplifying a nested if block


I have the following block of code:

if (x > 5)
{
    if (!DateTime.TryParse(y, out z))
        break;
    if (w.CompareTo(z) == -1)
        break;
}

Where x is an integer, y is a string, z and w are DateTime variables. The reason for the break; is that whole block resides within a loop.

Is there any way this could be simplified to make it easier to read?


Solution

  • More important: use descriptive variable names for w, x, y, z (hopefully these names were just for your example):

    You can also use the less than or greater than operators instead of CompareTo.

    if (x > 5)
    {
        bool isValidDate = DateTime.TryParse(y, out z);
        if (!isValidDate || z > w)
        {
            // comment like: stop processing if the current date 
            // is after the reference date, or if there was a parsing error
            break;
        }
    }