0

Consider this code:

class C
{
    private readonly CancellationTokenRegistration _ctr;
    public C(CancellationToken t) => _ctr = t.Register(...);
    private void Bla() => _ctr.Dispose();
}

Resharper warns (correctly, I think?) about a "possibly impure struct method called on readonly variable: struct value always copied before invocation".

But when readonly is removed from the declaration, the compiler may or may not emit a "IDE0044: Make field read only" message. Interestingly, it does so if .NET Standard 2.1 is targeted, but not if 2.0 (didn't check other targets).

Assuming Dispose() is impure (it might release the internal reference to the CancellationTokenSource and/or the callback), then I'd prefer it to be called on the field rather than a copy thereof, so no readonly.

Either way I have to suppress some message/warning, which is annoying.

Question: can anybody explain why the C# compiler does or doesn't emit the IDE0044 message depending on the target framework? Was there a fundamental change in the rules when/if methods of readonly structs are called on a copy?

tinudu
  • 1,139
  • 1
  • 10
  • 20
  • 2
    IDE0044 suffers from multiple accuracy issues. Disabling it so you'll never have to look at it again only takes [10 seconds](https://stackoverflow.com/questions/50399422/suppress-a-warning-for-all-projects-in-visual-studio). – Hans Passant Oct 18 '19 at 14:45

0 Answers0