[Proposal]: Raise compiler warning when the value of a parameter is changed. #9281
Replies: 5 comments 7 replies
-
You can add a warning for parameter reassignments through an analyzer. |
Beta Was this translation helpful? Give feedback.
-
I see some exceptions:
Can I avoid being warned by the compiler in such cases? |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
-
It would help to see an example or two, also consider there are Are you referring to calling |
Beta Was this translation helpful? Give feedback.
-
I do think this proposal has merit, in that is offers a potential way out of a deadlock we have in the language: On the one hand, a lot of people express their desire to prevent mutation of parameters. On the other hand, adding syntax for this (e.g. a Of course, making it an outright error in C# would be a massive breaking change, and as Jared calls out above, even a warning can be problematic. But issuing a diagnostic that users can then change the severity of could provide a way for people to protect their parameters without extra syntax, and for C# to embrace the scenario without punting to analyzers. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Introduction
This proposal suggests adding a new compiler warning that identifies when a parameter's value is changed within a method body. Modifying parameter values is a practice that can lead to code that is harder to understand, maintain, and debug. When a parameter's value is changed within a method, it creates several problems:
Proposed Solution
The proposal is to add a compiler warning when a parameter's value is directly modified. This would help developers identify and avoid this practice in favor of more maintainable alternatives.
This warning would be particularly valuable for code using primary constructors, which were introduced in C# 12. Primary constructors expose their parameters to the entire class scope, creating a significant risk for unintended modifications. It would help prevent subtle bugs that occur when primary constructor parameters are modified after class initialization. Since these parameters often represent dependencies or configuration that should remain constant throughout the object's lifecycle, detecting mutations would improve code reliability and maintainability.
Why a warning
A key advantage of implementing this as a compiler warning rather than a hard error is the flexibility it provides to developers. They can control how strictly they want to enforce this guideline:
/warnaserror:CSXXXX
) or in project files, enforcing immutable parameters as a strict coding standard.#pragma warning disable CSXXXX
.Beta Was this translation helpful? Give feedback.
All reactions