Skip to content

Files

Latest commit

 

History

History
65 lines (48 loc) · 1.67 KB

File metadata and controls

65 lines (48 loc) · 1.67 KB

Pattern: Call ToImmutableCollection on an ImmutableCollection value

Issue: -

Description

These extension methods are designed to convert a mutable collection to an immutable collection. However, the caller might accidentally pass in an immutable collection as input to these methods. This can represent a performance and/or a functional issue.

  • Performance issue: Unnecessary boxing, unboxing, and/or runtime type checks on an immutable collection.
  • Potential functional issue: Caller assumed to be operating on a mutable collection, when it actually had an immutable collection.

Example of incorrect code:

using System;
using System.Collections.Generic;
using System.Collections.Immutable;

public class C
{
    public void M(IEnumerable<int> collection, ImmutableArray<int> immutableArray)
    {
        // This is fine.
        M2(collection.ToImmutableArray());

        // This leads to CA2009.
        M2(immutableArray.ToImmutableArray());
    }

    private void M2(ImmutableArray<int> immutableArray)
    {
        Console.WriteLine(immutableArray.Length);
    }
}

Example of correct code:

using System;
using System.Collections.Generic;
using System.Collections.Immutable;

public class C
{
    public void M(IEnumerable<int> collection, ImmutableArray<int> immutableArray)
    {
        // This is fine.
        M2(collection.ToImmutableArray());

        // This is now fine.
        M2(immutableArray);
    }

    private void M2(ImmutableArray<int> immutableArray)
    {
        Console.WriteLine(immutableArray.Length);
    }
}

Further Reading