|
| 1 | +--- |
| 2 | +title: "CA1847: Use char literal for a single character lookup" |
| 3 | +description: "Use string.Contains(char) instead of string.Contains(string) when searching for a single character" |
| 4 | +ms.date: 03/03/2021 |
| 5 | +ms.topic: reference |
| 6 | +f1_keywords: |
| 7 | + - "CA1847" |
| 8 | +helpviewer_keywords: |
| 9 | + - "CA1847" |
| 10 | +author: MeikTranel |
| 11 | +dev_langs: |
| 12 | +- CSharp |
| 13 | +- VB |
| 14 | +--- |
| 15 | + |
| 16 | +# CA1847: Use string.Contains(char) instead of string.Contains(string) with single characters |
| 17 | + |
| 18 | +| | Value | |
| 19 | +|-|-| |
| 20 | +| **Rule ID** |CA1847| |
| 21 | +| **Category** |[Performance](performance-warnings.md)| |
| 22 | +| **Fix is breaking or non-breaking** |Non-breaking| |
| 23 | + |
| 24 | +## Cause |
| 25 | + |
| 26 | +`string.Contains(string)` is used when `string.Contains(char)` was available. |
| 27 | + |
| 28 | +## Rule description |
| 29 | + |
| 30 | +When searching for a single character, using `string.Contains(char)` offers better performance than `string.Contains(string)`. |
| 31 | + |
| 32 | +## How to fix violations |
| 33 | + |
| 34 | +In general, the rule is fixed simply by using a char literal instead of a string literal. |
| 35 | + |
| 36 | +```csharp |
| 37 | +public bool ContainsLetterI() |
| 38 | +{ |
| 39 | + var testString = "I am a test string."; |
| 40 | + return testString.Contains("I"); |
| 41 | +} |
| 42 | +``` |
| 43 | + |
| 44 | +```vb |
| 45 | +Public Function ContainsLetterI() As Boolean |
| 46 | + Dim testString As String = "I am a test string." |
| 47 | + Return testString.Contains("I") |
| 48 | +End Function |
| 49 | +``` |
| 50 | + |
| 51 | +This code can be changed to use a char literal instead. |
| 52 | + |
| 53 | +```csharp |
| 54 | +public bool ContainsLetterI() |
| 55 | +{ |
| 56 | + var testString = "I am a test string."; |
| 57 | + return testString.Contains('I'); |
| 58 | +} |
| 59 | +``` |
| 60 | + |
| 61 | +```vb |
| 62 | +Public Function ContainsLetterI() As Boolean |
| 63 | + Dim testString As String = "I am a test string." |
| 64 | + Return testString.Contains("I"c) |
| 65 | +End Function |
| 66 | +``` |
| 67 | + |
| 68 | +## When to suppress warnings |
| 69 | + |
| 70 | +Suppress a violation of this rule if you're not concerned about the performance impact of the search invocation in question. |
| 71 | + |
| 72 | +## See also |
| 73 | + |
| 74 | +- [Performance rules](performance-warnings.md) |
0 commit comments