rspec/rules/S2365/csharp/rule.adoc

65 lines
1.4 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2020-06-30 12:48:07 +02:00
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 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.
2021-02-02 15:02:10 +01:00
2021-01-27 13:42:22 +01:00
This rule detects calls to ``++ToList++``, ``++ToArray++`` and array ``++Clone++``.
2020-06-30 12:48:07 +02:00
=== Noncompliant code example
2020-06-30 12:48:07 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2020-06-30 12:48:07 +02:00
----
private List<string> _foo = new List<string> { "a", "b", "c" };
public IEnumerable<string> Foo // Noncompliant
{
get
{
return _foo.ToList();
}
}
private string[] _bar = new string[] { "a", "b", "c" };
public IEnumerable<string> Bar // Noncompliant
{
get
{
return (string[])_bar.Clone();
}
}
----
=== Compliant solution
2020-06-30 12:48:07 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2020-06-30 12:48:07 +02:00
----
private List<string> _foo = new List<string> { "a", "b", "c" };
private string[] _bar = new string[] { "a", "b", "c" };
public IEnumerable<string> GetFoo()
{
return _foo.ToList();
}
public IEnumerable<string> GetBar()
{
return (string[])_bar.Clone();
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::../message.adoc[]
include::../highlighting.adoc[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]