rspec/rules/S4004/rule.adoc

66 lines
1.5 KiB
Plaintext
Raw Permalink Normal View History

== Why is this an issue?
2021-01-27 13:42:22 +01:00
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++``).
2020-06-30 12:49:37 +02:00
2021-02-02 15:02:10 +01:00
2021-01-27 13:42:22 +01:00
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>++``.
2020-06-30 12:49:37 +02:00
=== Noncompliant code example
2020-06-30 12:49:37 +02:00
2022-02-04 17:28:24 +01:00
[source,text]
2020-06-30 12:49:37 +02:00
----
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
2020-06-30 12:49:37 +02:00
2022-02-04 17:28:24 +01:00
[source,text]
2020-06-30 12:49:37 +02:00
----
using System;
using System.Collections;
namespace MyLibrary
{
public class Foo
{
List<string> strings;
public List<string> SomeStrings
2020-06-30 12:49:37 +02:00
{
get { return strings; }
}
}
}
----
=== Exceptions
2020-06-30 12:49:37 +02:00
This rule does not raise issues for
2021-01-27 13:42:22 +01:00
* ``++string++``, ``++Array++`` and ``++PermissionSet,++``
* properties marked as ``++DataMemberAttribute++``
* classes marked as ``++Serializable++``
2020-06-30 12:49:37 +02:00
* properties overriding a base class member
* properties implementing interface