Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not access property multiple times in same method #471

Open
RalfKoban opened this issue Feb 17, 2022 · 2 comments
Open

Do not access property multiple times in same method #471

RalfKoban opened this issue Feb 17, 2022 · 2 comments

Comments

@RalfKoban
Copy link
Owner

It may happen that programmers write code as following:

public object SomeProperty { get; set; }

public void DoSomething()
{
    if (SomeProperty == null)
    {
    }

    if (SomeProperty is IAbc)
    {
    }

    if (SomeProperty is IXyz)
    {
    }
}

This leads to race-conditions in case SomeProperty gets changed while being inside the method.

Hence, they should assign the result of SomeProperty to a local variable and use that instead.

public object SomeProperty { get; set; }

public void DoSomething()
{
    var value = SomeProperty;

    if (value == null)
    {
    }

    if (value is IAbc)
    {
    }

    if (value is IXyz)
    {
    }
}
@RalfKoban
Copy link
Owner Author

Same applies for code like:

public void DoSomething()
{
    if (Abc.Def == null)
    {
        return;
    }

    foreach (var x in Abc.Def)
    { ... }
}

where Abc.Def represents an access to some properties.

@RalfKoban
Copy link
Owner Author

We should also check for coalescending access, such as in: if (Abc?.Def?.Ghi != null)

@RalfKoban RalfKoban moved this to Backlog in MiKo Analyzers Jul 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: Backlog
Development

No branches or pull requests

1 participant