Skip to content

Commit b9faab9

Browse files
authored
Add documentation for CA1864. (#36059)
1 parent ea53ce5 commit b9faab9

File tree

4 files changed

+103
-5
lines changed

4 files changed

+103
-5
lines changed
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
---
2+
title: "CA1864: Prefer the 'IDictionary.TryAdd(TKey, TValue)' method"
3+
description: "Learn about code analyzer rule CA1864 - Prefer the 'IDictionary.TryAdd(TKey, TValue)' method"
4+
ms.date: 06/30/2023
5+
ms.topic: reference
6+
f1_keywords:
7+
- CA1864
8+
- PreferDictionaryTryMethodsOverContainsKeyGuardAnalyzer
9+
helpviewer_keywords:
10+
- CA1864
11+
dev_langs:
12+
- CSharp
13+
- VB
14+
---
15+
16+
# CA1864: Prefer the 'IDictionary.TryAdd(TKey, TValue)' method
17+
18+
| | Value |
19+
| ----------------------------------- |----------------------------------------|
20+
| **Rule ID** | CA1864 |
21+
| **Category** | [Performance](performance-warnings.md) |
22+
| **Fix is breaking or non-breaking** | Non-breaking |
23+
| **Enabled by default in .NET 7** | No |
24+
25+
## Cause
26+
27+
<xref:System.Collections.Generic.Dictionary%602.Add%2A?displayProperty=nameWithType> is guarded by a <xref:System.Collections.Generic.Dictionary%602.ContainsKey(%600)?displayProperty=nameWithType> call.
28+
29+
## Rule description
30+
31+
Both <xref:System.Collections.Generic.Dictionary%602.ContainsKey(%600)?displayProperty=nameWithType> and <xref:System.Collections.Generic.Dictionary%602.Add%2A?displayProperty=nameWithType> perform a lookup, which is redundant. <xref:System.Collections.Generic.Dictionary%602.Add%2A?displayProperty=nameWithType> also throws an exception if the key is already present in the dictionary. It's more efficient to call <xref:System.Collections.Generic.Dictionary%602.TryAdd%2A?displayProperty=nameWithType>, which returns a Boolean value that indicates if the value was added or not. `TryAdd` doesn't overwrite the key's value if the key is already present.
32+
33+
## How to fix violations
34+
35+
Replace a call to <xref:System.Collections.Generic.Dictionary%602.ContainsKey(%600)?displayProperty=nameWithType> that's followed by a call to <xref:System.Collections.Generic.Dictionary%602.Add%2A?displayProperty=nameWithType> with a single call to <xref:System.Collections.Generic.Dictionary%602.TryAdd%2A?displayProperty=nameWithType>.
36+
37+
## Example
38+
39+
The following code snippet shows a violation of CA1864:
40+
41+
```csharp
42+
void Run(IDictionary<int, string> dictionary)
43+
{
44+
if(!dictionary.ContainsKey(2)) {
45+
dictionary.Add(2, "Hello World");
46+
}
47+
}
48+
```
49+
50+
```vb
51+
Sub Run(dictionary As IDictionary(Of Integer, String))
52+
If Not dictionary.ContainsKey(2) Then
53+
dictionary.Add(2, "Hello World")
54+
End If
55+
End Sub
56+
```
57+
58+
The following code snippet fixes the violation:
59+
60+
```csharp
61+
void Run(IDictionary<int, string> dictionary)
62+
{
63+
dictionary.TryAdd(2, "Hello World");
64+
}
65+
```
66+
67+
```vb
68+
Sub Run(dictionary As IDictionary(Of Integer, String))
69+
dictionary.TryAdd(2, "Hello World")
70+
End Sub
71+
```
72+
73+
## When to suppress warnings
74+
75+
It's safe to suppress this warning if performance isn't a concern and if you handle the exception that might be thrown by <xref:System.Collections.Generic.Dictionary%602.Add%2A?displayProperty=nameWithType>.
76+
77+
## Suppress a warning
78+
79+
If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.
80+
81+
```csharp
82+
#pragma warning disable CA1864
83+
// The code that's violating the rule is on this line.
84+
#pragma warning restore CA1864
85+
```
86+
87+
To disable the rule for a file, folder, or project, set its severity to `none` in the [configuration file](../configuration-files.md).
88+
89+
```ini
90+
[*.{cs,vb}]
91+
dotnet_diagnostic.CA1864.severity = none
92+
```
93+
94+
For more information, see [How to suppress code analysis warnings](../suppress-warnings.md).

docs/fundamentals/code-analysis/quality-rules/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,7 @@ The following table lists code quality analysis rules.
157157
> | [CA1859: Use concrete types when possible for improved performance](ca1859.md) | Code uses interface types or abstract types, leading to unnecessary interface calls or virtual calls. |
158158
> | [CA1860: Avoid using 'Enumerable.Any()' extension method](ca1860.md) | It's more efficient and clearer to use `Length`, `Count`, or `IsEmpty` (if possible) than to call <xref:System.Linq.Enumerable.Any%2A?displayProperty=nameWithType> to determine whether a collection type has any elements. |
159159
> | [CA1861: Avoid constant arrays as arguments](ca1861.md) | Constant arrays passed as arguments are not reused which implies a performance overhead. Consider extracting them to 'static readonly' fields to improve performance. |
160+
> | [CA1864: Prefer the 'IDictionary.TryAdd(TKey, TValue)' method](ca1864.md) | Both <xref:System.Collections.Generic.Dictionary%602.ContainsKey(%600)?displayProperty=nameWithType> and <xref:System.Collections.Generic.Dictionary%602.Add%2A?displayProperty=nameWithType> perform a lookup, which is redundant. It's is more efficient to call <xref:System.Collections.Generic.Dictionary%602.TryAdd%2A?displayProperty=nameWithType>, which returns a `bool` indicating if the value was added or not. `TryAdd` doesn't overwrite the key's value if the key is already present. |
160161
> | [CA2000: Dispose objects before losing scope](ca2000.md) | Because an exceptional event might occur that will prevent the finalizer of an object from running, the object should be explicitly disposed before all references to it are out of scope. |
161162
> | [CA2002: Do not lock on objects with weak identity](ca2002.md) |An object is said to have a weak identity when it can be directly accessed across application domain boundaries. A thread that tries to acquire a lock on an object that has a weak identity can be blocked by a second thread in a different application domain that has a lock on the same object. |
162163
> | [CA2007: Do not directly await a Task](ca2007.md) | An asynchronous method [awaits](../../../csharp/language-reference/operators/await.md) 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. |

docs/fundamentals/code-analysis/quality-rules/performance-warnings.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,3 +70,4 @@ Performance rules support high-performance libraries and applications.
7070
| [CA1859: Use concrete types when possible for improved performance](ca1859.md) | Code uses interface types or abstract types, leading to unnecessary interface calls or virtual calls. |
7171
| [CA1860: Avoid using 'Enumerable.Any()' extension method](ca1860.md) | It's more efficient and clearer to use `Length`, `Count`, or `IsEmpty` (if possible) than to call <xref:System.Linq.Enumerable.Any%2A?displayProperty=nameWithType> to determine whether a collection type has any elements. |
7272
| [CA1861: Avoid constant arrays as arguments](ca1861.md) | Constant arrays passed as arguments are not reused which implies a performance overhead. Consider extracting them to 'static readonly' fields to improve performance. |
73+
| [CA1864: Prefer the 'IDictionary.TryAdd(TKey, TValue)' method](ca1864.md) | Both <xref:System.Collections.Generic.Dictionary%602.ContainsKey(%600)?displayProperty=nameWithType> and <xref:System.Collections.Generic.Dictionary%602.Add%2A?displayProperty=nameWithType> perform a lookup, which is redundant. It's is more efficient to call <xref:System.Collections.Generic.Dictionary%602.TryAdd%2A?displayProperty=nameWithType>, which returns a `bool` indicating if the value was added or not. `TryAdd` doesn't overwrite the key's value if the key is already present. |

docs/navigate/tools-diagnostics/toc.yml

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -349,7 +349,7 @@ items:
349349
- name: Specialized diagnostics
350350
items:
351351
- name: Overview
352-
href: ../../core/diagnostics/specialized-diagnostics-overview.md
352+
href: ../../core/diagnostics/specialized-diagnostics-overview.md
353353
- name: Event Source
354354
items:
355355
- name: Overview
@@ -386,7 +386,7 @@ items:
386386
- name: Type-system events
387387
href: ../../fundamentals/diagnostics/runtime-type-events.md
388388
- name: Collect diagnostics in containers
389-
href: ../../core/diagnostics/diagnostics-in-containers.md
389+
href: ../../core/diagnostics/diagnostics-in-containers.md
390390
- name: Dumps
391391
items:
392392
- name: Overview
@@ -401,9 +401,9 @@ items:
401401
- name: Collect dumps on crash
402402
href: ../../core/diagnostics/collect-dumps-crash.md
403403
- name: Symbols
404-
href: ../../core/diagnostics/symbols.md
404+
href: ../../core/diagnostics/symbols.md
405405
- name: EventPipe
406-
href: ../../core/diagnostics/eventpipe.md
406+
href: ../../core/diagnostics/eventpipe.md
407407
- name: Diagnostic port
408408
items:
409409
- name: Overview
@@ -418,7 +418,7 @@ items:
418418
- name: DiagnosticSource and DiagnosticListener
419419
items:
420420
- name: Get started
421-
href: ../../core/diagnostics/diagnosticsource-diagnosticlistener.md
421+
href: ../../core/diagnostics/diagnosticsource-diagnosticlistener.md
422422
- name: .NET CLI global tools
423423
items:
424424
- name: Overview
@@ -801,6 +801,8 @@ items:
801801
href: ../../fundamentals/code-analysis/quality-rules/ca1860.md
802802
- name: CA1861
803803
href: ../../fundamentals/code-analysis/quality-rules/ca1861.md
804+
- name: CA1864
805+
href: ../../fundamentals/code-analysis/quality-rules/ca1864.md
804806
- name: SingleFile rules
805807
items:
806808
- name: Overview

0 commit comments

Comments
 (0)