dotnet / dotnet/roslynator

Analyzer + codefix: Mark objects used for locking as readonly (new or RCS1169 derivative)

Open
#325 0 comments 1 reaction 0 assignees View on GitHub
Area-Analyzers Feature Request
Dominant language
C#
Stars
3.5k
Forks
294
Avg merge
2h 30m
Merged PRs (30d)
4

Description

Consider:

```
object locker = new object();

void LockedAction()
{
lock (locker)
{
// ... do something requiring locking...
}
}
```

But any code can reassign the value of `locker`:

```
void SomethingElse()
{
locker = new object();
}
```

The end result is that `LockedAction` is no longer thread-safe and Bad Things™ will happen when it is invoked concurrently.

To prevent this bug, `locker` should be declared as `readonly` so that it can never be reassigned:

```
readonly object locker = new object();

void SomethingElse()
{
locker = new object(); // compile error
}
```

I'm aware this is already covered by [RSC1169](https://github.com/JosefPihrt/Roslynator/blob/master/docs/analyzers/RCS1169.md), but this is a special and IMO more important case.

Contributor guide

Open the contributing guide

Research direction

Start by reading docs/analyzers/RCS1169.md, which the issue identifies as related work, and compare its scope with the locking-specific behavior described here. Determine how the analyzer and codefix should recognize objects used in lock statements and make the declaration readonly; done means the unsafe reassignment is diagnosed or prevented by the proposed fix.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.