Skip to content

Gendarme.Rules.Performance.AvoidReturningArraysOnPropertiesRule(git)

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

AvoidReturningArraysOnPropertiesRule

Assembly: Gendarme.Rules.Performance
Version: git

Description

This rule check for properties which return arrays. This can be a problem because properties are supposed to execute very quickly so it's likely that this property is returning a reference to the internal state of the object. This means that the caller can change the object's internal state via a back-door channel which is usually a very bad thing and it means that the array's contents may change unexpectedly if the caller holds onto the array. The preferred approach is to either return a read-only collection or to change the property to a method and return a copy of the array (it's important to use a method so that callers are not misled about the performance of the property).

Examples

Bad example:

public byte[] Foo {
    get {
        // return the data inside the instance
        return foo;
    }
}
public byte[] Bar {
    get {
        // return a copy of the instance's data
        // (this is bad because users expect properties to execute quickly)
        return (byte[]) bar.Clone ();
    }
}

Good example:

public byte[] GetFoo ()
{
    return (byte[]) foo.Clone ();
}
public byte[] GetFoo ()
{
    return (byte[]) bar.Clone ();
}

Source code

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

Clone this wiki locally