Skip to content

Commit 4a551f3

Browse files
authored
Merge pull request #6481 from mavasani/Doc_CA2009
Add documentation for CA2009
2 parents 1b7412f + 43cde98 commit 4a551f3

File tree

5 files changed

+124
-1
lines changed

5 files changed

+124
-1
lines changed

docs/code-quality/ca2009.md

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
---
2+
title: 'CA2009: Do not call ToImmutableCollection on an ImmutableCollection value'
3+
ms.date: 04/29/2020
4+
ms.topic: reference
5+
f1_keywords:
6+
- CA2009
7+
- DoNotCallToImmutableCollectionOnAnImmutableCollectionValueAnalyzer
8+
helpviewer_keywords:
9+
- CA2009
10+
author: mavasani
11+
ms.author: mavasani
12+
manager: jillfra
13+
---
14+
# CA2009: Do not call ToImmutableCollection on an ImmutableCollection value
15+
16+
|||
17+
|-|-|
18+
|TypeName|DoNotCallToImmutableCollectionOnAnImmutableCollectionValueAnalyzer|
19+
|CheckId|CA2009|
20+
|Category|Microsoft.Reliability|
21+
|Breaking change|Non-breaking|
22+
23+
## Cause
24+
25+
`ToImmutable` method was unnecessarily called on an immutable collection from <xref:System.Collections.Immutable> namespace.
26+
27+
## Rule description
28+
29+
<xref:System.Collections.Immutable> namespace contains types that define immutable collections. This rule analyzes the following immutable collection types:
30+
31+
- <xref:System.Collections.Immutable.ImmutableArray%601?displayProperty=fullName>
32+
- <xref:System.Collections.Immutable.ImmutableList%601?displayProperty=fullName>
33+
- <xref:System.Collections.Immutable.ImmutableHashSet%601?displayProperty=fullName>
34+
- <xref:System.Collections.Immutable.ImmutableSortedSet%601?displayProperty=fullName>
35+
- <xref:System.Collections.Immutable.ImmutableDictionary%602?displayProperty=fullName>
36+
- <xref:System.Collections.Immutable.ImmutableSortedDictionary%602?displayProperty=fullName>
37+
38+
These types define extension methods that create a new immutable collection from an existing <xref:System.Collections.Generic.IEnumerable%601> collection.
39+
40+
- <xref:System.Collections.Immutable.ImmutableArray%601> defines <xref:System.Collections.Immutable.ImmutableArray.ToImmutableArray%2A>.
41+
- <xref:System.Collections.Immutable.ImmutableList%601> defines <xref:System.Collections.Immutable.ImmutableList.ToImmutableList%2A>.
42+
- <xref:System.Collections.Immutable.ImmutableHashSet%601> defines <xref:System.Collections.Immutable.ImmutableHashSet.ToImmutableHashSet%2A>.
43+
- <xref:System.Collections.Immutable.ImmutableSortedSet%601> defines <xref:System.Collections.Immutable.ImmutableSortedSet.ToImmutableSortedSet%2A>.
44+
- <xref:System.Collections.Immutable.ImmutableDictionary%602> defines <xref:System.Collections.Immutable.ImmutableDictionary.ToImmutableDictionary%2A>.
45+
- <xref:System.Collections.Immutable.ImmutableSortedDictionary%602> defines <xref:System.Collections.Immutable.ImmutableSortedDictionary.ToImmutableSortedDictionary%2A>.
46+
47+
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.
48+
49+
- Performance issue: Unnecessary creation of a duplicate immutable collection. The original collection was already immutable and can be used directly.
50+
- Potential functional issue: Caller assumed to be operating on a mutable collection, when it actually had an immutable collection.
51+
52+
> [!NOTE]
53+
> Rule CA2009 is not available in legacy analysis. It was first introduced in [FxCop analyzers](https://www.nuget.org/packages/Microsoft.CodeAnalysis.FxCopAnalyzers) version 2.9.6.
54+
55+
## How to fix violations
56+
57+
To fix violations, remove the redundant `ToImmutable` call on an immutable collection. For example, the following two code snippets show a violation of the rule and how to fix them:
58+
59+
```csharp
60+
using System;
61+
using System.Collections.Generic;
62+
using System.Collections.Immutable;
63+
64+
public class C
65+
{
66+
public void M(IEnumerable<int> collection, ImmutableArray<int> immutableArray)
67+
{
68+
// This is fine.
69+
M2(collection.ToImmutableArray());
70+
71+
// This leads to CA2009.
72+
M2(immutableArray.ToImmutableArray());
73+
}
74+
75+
private void M2(ImmutableArray<int> immutableArray)
76+
{
77+
Console.WriteLine(immutableArray.Length);
78+
}
79+
}
80+
```
81+
82+
83+
```csharp
84+
using System;
85+
using System.Collections.Generic;
86+
using System.Collections.Immutable;
87+
88+
public class C
89+
{
90+
public void M(IEnumerable<int> collection, ImmutableArray<int> immutableArray)
91+
{
92+
// This is fine.
93+
M2(collection.ToImmutableArray());
94+
95+
// This is now fine.
96+
M2(immutableArray);
97+
}
98+
99+
private void M2(ImmutableArray<int> immutableArray)
100+
{
101+
Console.WriteLine(immutableArray.Length);
102+
}
103+
}
104+
```
105+
106+
> [!TIP]
107+
> A code fix is available for this rule in Visual Studio. To use it, position the cursor on the violation and press **Ctrl**+**.** (period). Choose **Remove redundant call** from the list of options that's presented.
108+
>
109+
> ![Code fix for CA2009 - Do not call ToImmutableCollection on an ImmutableCollection value](media/ca2009-codefix.png)
110+
111+
## When to suppress warnings
112+
113+
Do not suppress violations from this rule, unless you're not concerned about the performance impact from unnecessary allocations of immutable collections.
114+
115+
## See also
116+
117+
- [Reliability warnings](reliability-warnings.md)
118+
- [Performance warnings](performance-warnings.md)

docs/code-quality/code-analysis-warnings-for-managed-code-by-checkid.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,7 @@ f1_keywords:
172172
- CA2004
173173
- CA2006
174174
- CA2007
175+
- CA2009
175176
- CA2100
176177
- CA2101
177178
- CA2102
@@ -277,7 +278,6 @@ The following table lists Code Analysis warnings for managed code by the CheckId
277278

278279
| CheckId | Warning | Description |
279280
|---------| - | - |
280-
| CA2007 | [CA2007: Do not directly await a Task](ca2007.md) | An asynchronous method [awaits](/dotnet/csharp/language-reference/keywords/await) a <xref:System.Threading.Tasks.Task> directly. When an asynchronous method awaits a <xref:System.Threading.Tasks.Task> directly, continuation occurs in the same thread that created the task. This behavior can be costly in terms of performance and can result in a deadlock on the UI thread. Consider calling <xref:System.Threading.Tasks.Task.ConfigureAwait(System.Boolean)?displayProperty=nameWithType> to signal your intention for continuation. |
281281
| CA1000 | [CA1000: Do not declare static members on generic types](../code-quality/ca1000.md) | When a static member of a generic type is called, the type argument must be specified for the type. When a generic instance member that does not support inference is called, the type argument must be specified for the member. In these two cases, the syntax for specifying the type argument is different and easily confused. |
282282
| CA1001 | [CA1001: Types that own disposable fields should be disposable](../code-quality/ca1001.md) | A class declares and implements an instance field that is a System.IDisposable type, and the class does not implement IDisposable. A class that declares an IDisposable field indirectly owns an unmanaged resource and should implement the IDisposable interface. |
283283
| CA1002 | [CA1002: Do not expose generic lists](../code-quality/ca1002.md) | System.Collections.Generic.List<(Of \<(T>)>) is a generic collection that is designed for performance, not inheritance. Therefore, List does not contain any virtual members. The generic collections that are designed for inheritance should be exposed instead. |
@@ -435,6 +435,8 @@ The following table lists Code Analysis warnings for managed code by the CheckId
435435
| CA2003 |[CA2003: Do not treat fibers as threads](../code-quality/ca2003.md) | A managed thread is being treated as a [!INCLUDE[TLA2#tla_win32](../code-quality/includes/tla2sharptla_win32_md.md)] thread. |
436436
| CA2004 | [CA2004: Remove calls to GC.KeepAlive](../code-quality/ca2004.md) | If you convert to SafeHandle usage, remove all calls to GC.KeepAlive (object). In this case, classes should not have to call GC.KeepAlive. This assumes they do not have a finalizer but rely on SafeHandle to finalize the OS handle for them. |
437437
| CA2006 | [CA2006: Use SafeHandle to encapsulate native resources](../code-quality/ca2006.md) | Use of IntPtr in managed code might indicate a potential security and reliability problem. All uses of IntPtr must be reviewed to determine whether use of a SafeHandle, or similar technology, is required in its place. |
438+
| CA2007 | [CA2007: Do not directly await a Task](ca2007.md) | An asynchronous method [awaits](/dotnet/csharp/language-reference/keywords/await) a <xref:System.Threading.Tasks.Task> directly. When an asynchronous method awaits a <xref:System.Threading.Tasks.Task> directly, continuation occurs in the same thread that created the task. This behavior can be costly in terms of performance and can result in a deadlock on the UI thread. Consider calling <xref:System.Threading.Tasks.Task.ConfigureAwait(System.Boolean)?displayProperty=nameWithType> to signal your intention for continuation. |
439+
| CA2009 | [CA2009: Do not call ToImmutableCollection on an ImmutableCollection value](ca2009.md) | `ToImmutable` method was unnecessarily called on an immutable collection from <xref:System.Collections.Immutable> namespace. |
438440
| CA2100 | [CA2100: Review SQL queries for security vulnerabilities](../code-quality/ca2100.md) | A method sets the System.Data.IDbCommand.CommandText property by using a string that is built from a string argument to the method. This rule assumes that the string argument contains user input. A SQL command string that is built from user input is vulnerable to SQL injection attacks. |
439441
| CA2101 |[CA2101: Specify marshaling for P/Invoke string arguments](../code-quality/ca2101.md) | A platform invoke member allows partially trusted callers, has a string parameter, and does not explicitly marshal the string. This can cause a potential security vulnerability. |
440442
| CA2102 | [CA2102: Catch non-CLSCompliant exceptions in general handlers](../code-quality/ca2102.md) | A member in an assembly that is not marked by using the RuntimeCompatibilityAttribute or is marked RuntimeCompatibility(WrapNonExceptionThrows = false) contains a catch block that handles System.Exception and does not contain an immediately following general catch block. |
27.3 KB
Loading

docs/code-quality/reliability-warnings.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,4 @@ Reliability warnings support library and application reliability, such as correc
2828
|[CA2004: Remove calls to GC.KeepAlive](../code-quality/ca2004.md)|If you are converting to SafeHandle usage, remove all calls to GC.KeepAlive (object). In this case, classes should not have to call GC.KeepAlive, assuming they do not have a finalizer but rely on SafeHandle to finalize the OS handle for them.|
2929
|[CA2006: Use SafeHandle to encapsulate native resources](../code-quality/ca2006.md)|Use of IntPtr in managed code might indicate a potential security and reliability problem. All uses of IntPtr must be reviewed to determine whether use of a SafeHandle, or similar technology, is required in its place.|
3030
|[CA2007: Do not directly await a Task](../code-quality/ca2007.md)|An asynchronous method [awaits](/dotnet/csharp/language-reference/keywords/await) a <xref:System.Threading.Tasks.Task> directly.|
31+
|[CA2009: Do not call ToImmutableCollection on an ImmutableCollection value](../code-quality/ca2009.md)|`ToImmutable` method was unnecessarily called on an immutable collection from <xref:System.Collections.Immutable> namespace.|

docs/code-quality/toc.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -575,6 +575,8 @@
575575
href: ca2006.md
576576
- name: "CA2007: Do not directly await a Task"
577577
href: ca2007.md
578+
- name: "CA2009: Do not call ToImmutableCollection on an ImmutableCollection value"
579+
href: ca2009.md
578580
- name: Security warnings
579581
items:
580582
- name: Overview

0 commit comments

Comments
 (0)