Make it an error to invoke non-readonly methods on a readonly field #8355
-
Hey folks, there may be a legitimate use case for this that I'm missing, if so, sorry in advance. I also tried looking for an existing discussion on this, but couldn't find one. My suggestion is to make this an error: struct Bar
{
void NonReadonlyMethod() {}
}
/*readonly*/ struct Foo
{
/*readonly*/ Bar _bar;
readonly void ReadonlyMethod() => _bar.NonReadonlyMethod(); // error
readonly void ReadonlyMethod()
{
var copy = _bar;
copy.NonReadonlyMethod(); // legal
}
} I have fallen quite a few times into the trap of introducing Unless I'm missing something obvious here, even when it's not a bug I think I'd much prefer the compiler force me to make an explicit copy (such as when I know an API that I don't control does not change state but hasn't been marked These issues are currently solved by analyzers, and AFAIK there is no official one that checks for this shipped with the .NET SDK. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 100 replies
-
There is nothing wrong calling a non-readonly method on a readonly field. Indeed, it's super common. Consider how often people may call things like GetHashCode, ToString, or even Equals on these methods. All of which are not commonly exported as something readonly.
Yes, this is the right way to do things. Having the language fail here would break everything. |
Beta Was this translation helpful? Give feedback.
There is nothing wrong calling a non-readonly method on a readonly field. Indeed, it's super common. Consider how often people may call things like GetHashCode, ToString, or even Equals on these methods. All of which are not commonly exported as something readonly.
Yes, this is the right way to do things. Having the language fail here would break everything.