
## Review A dedicated reviewer checked the rule description successfully for: - [ ] logical errors and incorrect information - [ ] information gaps and missing content - [ ] text style and tone - [ ] PR summary and labels follow [the guidelines](https://github.com/SonarSource/rspec/#to-modify-an-existing-rule)
66 lines
1.5 KiB
Plaintext
66 lines
1.5 KiB
Plaintext
== Why is this an issue?
|
||
|
||
A writable collection property can be replaced by a completely different collection. Making it ``++readonly++`` prevents that while still allowing individual members to be set. If you want to allow the replacement of the whole collection the recommended pattern is to implement a method to remove all the elements (e.g. ``++System.Collections.List<T>.Clear++``) and a method to populate the collection (e.g. ``++System.Collections.List<T>.AddRange++``).
|
||
|
||
|
||
This rule raises an issue when an externally visible writable property is of a type that implements ``++System.Collections.ICollection++`` or ``++System.Collections.Generic.ICollection<T>++``.
|
||
|
||
|
||
=== Noncompliant code example
|
||
|
||
[source,text]
|
||
----
|
||
using System;
|
||
using System.Collections;
|
||
|
||
namespace MyLibrary
|
||
{
|
||
public class Foo
|
||
{
|
||
List<string> strings;
|
||
|
||
public List<string> SomeStrings
|
||
{
|
||
get { return strings; }
|
||
set { strings = value; } // Noncompliant
|
||
}
|
||
}
|
||
}
|
||
----
|
||
|
||
|
||
=== Compliant solution
|
||
|
||
[source,text]
|
||
----
|
||
using System;
|
||
using System.Collections;
|
||
|
||
namespace MyLibrary
|
||
{
|
||
public class Foo
|
||
{
|
||
List<string> strings;
|
||
|
||
public List<string> SomeStrings
|
||
{
|
||
get { return strings; }
|
||
}
|
||
}
|
||
}
|
||
----
|
||
|
||
|
||
=== Exceptions
|
||
|
||
This rule does not raise issues for
|
||
|
||
* ``++string++``, ``++Array++`` and ``++PermissionSet,++``
|
||
* properties marked as ``++DataMemberAttribute++``
|
||
* classes marked as ``++Serializable++``
|
||
* properties overriding a base class member
|
||
* properties implementing interface
|
||
|
||
|
||
|