org.sonar.plugins.csharp.S2365.html Maven / Gradle / Ivy
Why is this an issue?
Most developers expect property access to be as efficient as field access. However, if a property returns a copy of an array or collection, it will
be much slower than a simple field access, contrary to the caller’s likely expectations. Therefore, such properties should be refactored into methods
so that callers are not surprised by the unexpectedly poor performance.
This rule tracks calls to the following methods inside properties:
How to fix it
Code examples
Noncompliant code example
private List<string> foo = new List<string> { "a", "b", "c" };
private string[] bar = new string[] { "a", "b", "c" };
public IEnumerable<string> Foo => foo.ToList(); // Noncompliant: collection foo is copied
public IEnumerable<string> Bar => (string[])bar.Clone(); // Noncompliant: array bar is copied
Compliant solution
private List<string> foo = new List<string> { "a", "b", "c" };
private string[] bar = new string[] { "a", "b", "c" };
public IEnumerable<string> GetFoo() => foo.ToList();
public IEnumerable<string> GetBar() => (string[])bar.Clone();
Resources
Documentation
© 2015 - 2024 Weber Informatics LLC | Privacy Policy