Skip to content

Gendarme.Rules.Design.DoNotDeclareSettersOnCollectionPropertiesRule(git)

Sebastien Pouliot edited this page Mar 18, 2011 · 1 revision

DoNotDeclareSettersOnCollectionPropertiesRule

Assembly: Gendarme.Rules.Design
Version: git

Description

The rule detect System.Collections.ICollection and [[System.Collections.Generic.ICollection<T>|http://msdn.microsoft.com/library/System.Collections.Generic.ICollection.aspx]] properties that declare a visible setter. There is rarely a need to be able to replace the collection (e.g. most collections provide a Clear method) and having a getter only does not prevent the consumer from adding and removing items in the collection. Also read-only properties have special support for binary and XML serialization, making your code more useful. A special exception is made for System.Security.PermissionSet and types that derives from it.

Examples

Bad example:

public class Holder {
public string Name { get; set; }
public ICollection<string> List { get; set; }
}
public static Holder Copy (Holder h)
{
Holder copy = new Holder ();
copy.Name = h.Name;
// bad, same list would be shared between instances
copy.List = h.List;
copy.List.AddRange (h.List);
return copy;
}

Good example:

public class Holder {
    List<string> list;
    public Holder ()
    {
        list = new List<string> ();
    }
public string Name { get; set; }
public ICollection<string> List {
get { return list; }
}
}
public static Holder Copy (Holder h)
{
Holder copy = new Holder ();
copy.Name = h.Name;
copy.List.AddRange (h.List);
return copy;
}

Source code

You can browse the latest source code of this rule on github.com

Clone this wiki locally