All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.csharp.S4004.html Maven / Gradle / Ivy

There is a newer version: 10.2.0.105762
Show newest version

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

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

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

 





© 2015 - 2024 Weber Informatics LLC | Privacy Policy