1

i am fully aware about nullabe context and how to deal with it in c#, even with this i have review this microsoft official tutorial and also this question on stackoverflow, but there is a thing that i really can not figure out why!!??
in a nullable context enabled code the following code works good and with no problem:

List<DateStepStatus> OperationOnTimeLine_success (List<DateStepStatus> timeLine)
{
    for (int i = 0; i < timeLine.Count; i++)
    {
        DateTime dateTime = timeLine[i].dateTime;
        if (DateTime.Today >= dateTime)
        {
            var abc = timeLine[i].stepStatus;
            if (abc is not null)
            {
                abc.Status = Status.Succeed;
            }

        }
        else continue;
    }
    return timeLine;
}

but this code has a warning:

List<DateStepStatus> OperationOnTimeLine_success (List<DateStepStatus> timeLine)
{
    for (int i = 0; i < timeLine.Count; i++)
    {
        DateTime dateTime = timeLine[i].dateTime;
        if (DateTime.Today >= dateTime)
        {
            if (timeLine[i].stepStatus is not null)
            {
                timeLine[i].stepStatus.Status = Status.Succeed;// bad-green warning goes under "timeLine[i].stepStatus" part
            }

        }
        else continue;
    }
    return timeLine;
}

this really is annoying ! if i just use a var (like abc), warning goes away, but if i want to do the same thing directly warning comes back again!

  • Can you provide a [mcve]? There are any number of subtleties that could affect this. (I'd suggest using a pattern variable to be honest - then you don't need the expression duplication at all... but that's a slightly different matter.) – Jon Skeet Jun 27 '22 at 09:59
  • 3
    The language does not guarantee that the property `stepStatus` returns the same value when the getter is called multiple times. – Klaus Gütter Jun 27 '22 at 10:02
  • @KlausGütter, great, it seems reasonable and i will accept it if you post this as an answer, tnx – TechDogLover OR kiaNasirzadeh Jun 27 '22 at 10:07

1 Answers1

2

The C# language does not guarantee that the property stepStatus returns the same value when the getter is called multiple times. Therefore null-checking it once is no proof that it will not be null the second time.

Klaus Gütter
  • 11,151
  • 6
  • 31
  • 36