CA2104: Do not declare read only mutable reference types
Cause
An externally visible type contains an externally visible read-only field that is a mutable reference type.
Rule Description
A mutable type is a type whose instance data can be modified. The System.Text.StringBuilder class is an example of a mutable reference type. It contains members that can change the value of an instance of the class. An example of an immutable reference type is the System.String class. After it has been instantiated, its value can never change.
The read-only modifier (readonly in C#, ReadOnly in Visual Basic, and const in C++) on a reference type field (pointer in C++) prevents the field from being replaced by a different instance of the reference type. However, the modifier does not prevent the instance data of the field from being modified through the reference type.
Read-only array fields are exempt from this rule but instead cause a violation of the CA2105: Array fields should not be read only rule.
How to Fix Violations
To fix a violation of this rule, remove the read-only modifier or, if a breaking change is acceptable, replace the field with an immutable type.
С одной стороны, как бы логично, но с другой как бы противоречит практике .....
Здравствуйте, vladpol, Вы писали:
V>С одной стороны, как бы логично...
Да вроде с любой стороны нелогично. То, что readonly не обеспечивает глубокую иммутабельность, не значит, что бесполезно использовать хотя бы ссылочную иммутабельность.
Глаза у меня добрые, но рубашка — смирительная!
Re: Майкрософт считает что readoly для reference типов не имеет смысла
Здравствуйте, vladpol, Вы писали:
V>С одной стороны, как бы логично, но с другой как бы противоречит практике .....
Как обычно, it depends. По умолчанию правило не включено, если в команде принято подобное соглашение — включаем, если нет — не включаем.
На мой взгляд, количество ложных срабатываний у этого правила слишком велико; плюс, оно усложняет код. Вместо банального readonly + проверки на null в конструкторе теперь нужно следить за всем кодом внутри класса, т.к. никаких гарантий, что очередной хотфикс не закинет null в поле у нас нет.
Но не всё так мрачно В восьмом шарпе появятся nullable references, которые слегка упростят проблему, ну а immutable types (для них таймлайн ещё не определён) окончательно закроют вопрос.
Re: Майкрософт считает что readoly для reference типов не имеет смысла
Здравствуйте, vladpol, Вы писали:
V>Коллега откопал следующее правило анализатор V> V>
CA2104: Do not declare read only mutable reference types
V>Cause
V>An externally visible type contains an externally visible read-only field that is a mutable reference type.
V>Rule Description
V>A mutable type is a type whose instance data can be modified. The System.Text.StringBuilder class is an example of a mutable reference type. It contains members that can change the value of an instance of the class. An example of an immutable reference type is the System.String class. After it has been instantiated, its value can never change.
V>The read-only modifier (readonly in C#, ReadOnly in Visual Basic, and const in C++) on a reference type field (pointer in C++) prevents the field from being replaced by a different instance of the reference type. However, the modifier does not prevent the instance data of the field from being modified through the reference type.
V>Read-only array fields are exempt from this rule but instead cause a violation of the CA2105: Array fields should not be read only rule.
V>How to Fix Violations
V>To fix a violation of this rule, remove the read-only modifier or, if a breaking change is acceptable, replace the field with an immutable type.
V>С одной стороны, как бы логично, но с другой как бы противоречит практике .....
Вероятно, переживают за неучей, которые думают, что readonly распространяется на весь объект
Здравствуйте, karbofos42, Вы писали:
K>Вероятно, переживают за неучей, которые думают, что readonly распространяется на весь объект :xz:
Да, в стародавней книжке «Framework Design Guidelines» именно так рационализируют эту рекомендацию. Впрочем, на GitHub в исходниках разных библиотек от Майкрософт можно увидеть, что на это замшелое правило они почти везде кладут readonly.