include::../why-dotnet.adoc[]

== How to fix it

=== Code examples

==== Noncompliant code example

[source,csharp,diff-id=1,diff-type=noncompliant]
----
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

[source,csharp,diff-id=1,diff-type=compliant]
----
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

* https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties[Properties (C# Programming Guide)]
* https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/fields[Fields (C# Programming Guide)]
* https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/collections[Collections (C#)]
* https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.tolist[Enumerable.ToList]
* https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.toarray[Enumerable.ToArray]
* https://learn.microsoft.com/en-us/dotnet/api/system.array.clone[Array.Clone]

include::../rspecator.adoc[]
