简体   繁体   中英

nullable context doesn't work properly in c#

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM