- 
                Notifications
    You must be signed in to change notification settings 
- Fork 6.1k
Document code analysis rules CA1873, CA1874, CA1875, CA2023 #49492
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Merged
      
      
    
  
     Merged
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            8 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      456ccb1
              
                Initial plan
              
              
                Copilot 3b69546
              
                Add documentation for four new code analysis rules
              
              
                Copilot d81a82c
              
                Add ms.topic and author metadata to new rules
              
              
                Copilot 8e317b8
              
                human edits
              
              
                gewarren 7aff30a
              
                use backticks around code
              
              
                gewarren c2121b1
              
                fix lint
              
              
                gewarren 2b45394
              
                Apply suggestions from code review
              
              
                gewarren 605a3ef
              
                fix xref
              
              
                gewarren File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
        
          
  
    
      
          
            172 changes: 172 additions & 0 deletions
          
          172 
        
  docs/fundamentals/code-analysis/quality-rules/ca1873.md
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,172 @@ | ||
| --- | ||
| title: "CA1873: Avoid potentially expensive logging (code analysis)" | ||
| description: "Learn about code analysis rule CA1873: Avoid potentially expensive logging" | ||
| ms.date: 10/27/2025 | ||
| ms.topic: reference | ||
| f1_keywords: | ||
| - CA1873 | ||
| - AvoidPotentiallyExpensiveCallWhenLoggingAnalyzer | ||
| helpviewer_keywords: | ||
| - CA1873 | ||
| dev_langs: | ||
| - CSharp | ||
| - VB | ||
|         
                  gewarren marked this conversation as resolved.
              Show resolved
            Hide resolved | ||
| ai-usage: ai-generated | ||
| --- | ||
|  | ||
| # CA1873: Avoid potentially expensive logging | ||
|  | ||
| | Property | Value | | ||
| |-------------------------------------|----------------------------------------| | ||
| | **Rule ID** | CA1873 | | ||
| | **Title** | Avoid potentially expensive logging | | ||
| | **Category** | [Performance](performance-warnings.md) | | ||
| | **Fix is breaking or non-breaking** | Non-breaking | | ||
| | **Enabled by default in .NET 10** | As suggestion | | ||
|  | ||
| ## Cause | ||
|  | ||
| In many situations, logging is disabled or set to a log level that results in an unnecessary evaluation for logging arguments. | ||
|  | ||
| ## Rule description | ||
|  | ||
| When logging methods are called, their arguments are evaluated regardless of whether the logging level is enabled. This can result in expensive operations being executed even when the log message won't be written. For better performance, guard expensive logging calls with a check to <xref:Microsoft.Extensions.Logging.ILogger.IsEnabled%2A> or use the `LoggerMessage` pattern. | ||
|  | ||
| ## How to fix violations | ||
|  | ||
| To fix a violation of this rule, use one of the following approaches: | ||
|  | ||
| - Guard the logging call with a check to <xref:Microsoft.Extensions.Logging.ILogger.IsEnabled%2A>. | ||
| - Use the `LoggerMessage` pattern with <xref:Microsoft.Extensions.Logging.LoggerMessageAttribute>. | ||
| - Ensure expensive operations aren't performed in logging arguments unless necessary. | ||
|  | ||
| ## Example | ||
|  | ||
| The following code snippet shows violations of CA1873: | ||
|  | ||
| ```csharp | ||
| using Microsoft.Extensions.Logging; | ||
|  | ||
| class Example | ||
| { | ||
| private readonly ILogger _logger; | ||
|  | ||
| public Example(ILogger<Example> logger) | ||
| { | ||
| _logger = logger; | ||
| } | ||
|  | ||
| public void ProcessData(int[] data) | ||
| { | ||
| // Violation: expensive operation in logging argument. | ||
| _logger.LogDebug($"Processing {string.Join(", ", data)} items"); | ||
|  | ||
| // Violation: object creation in logging argument. | ||
| _logger.LogTrace("Data: {Data}", new { Count = data.Length, Items = data }); | ||
| } | ||
| } | ||
| ``` | ||
|  | ||
| ```vb | ||
| Imports Microsoft.Extensions.Logging | ||
|  | ||
| Class Example | ||
| Private ReadOnly _logger As ILogger | ||
|  | ||
| Public Sub New(logger As ILogger(Of Example)) | ||
| _logger = logger | ||
| End Sub | ||
|  | ||
| Public Sub ProcessData(data As Integer()) | ||
| ' Violation: expensive operation in logging argument. | ||
| _logger.LogDebug($"Processing {String.Join(", ", data)} items") | ||
|  | ||
| ' Violation: object creation in logging argument. | ||
| _logger.LogTrace("Data: {Data}", New With {.Count = data.Length, .Items = data}) | ||
| End Sub | ||
| End Class | ||
| ``` | ||
|  | ||
| The following code snippet fixes the violations: | ||
|  | ||
| ```csharp | ||
| using Microsoft.Extensions.Logging; | ||
|  | ||
| class Example | ||
| { | ||
| private readonly ILogger _logger; | ||
|  | ||
| public Example(ILogger<Example> logger) | ||
| { | ||
| _logger = logger; | ||
| } | ||
|  | ||
| public void ProcessData(int[] data) | ||
| { | ||
| // Fixed: guard with IsEnabled check. | ||
| if (_logger.IsEnabled(LogLevel.Debug)) | ||
| { | ||
| _logger.LogDebug($"Processing {string.Join(", ", data)} items"); | ||
| } | ||
|  | ||
| // Fixed: guard with IsEnabled check. | ||
| if (_logger.IsEnabled(LogLevel.Trace)) | ||
| { | ||
| _logger.LogTrace("Data: {Data}", new { Count = data.Length, Items = data }); | ||
| } | ||
| } | ||
| } | ||
| ``` | ||
|  | ||
| ```vb | ||
| Imports Microsoft.Extensions.Logging | ||
|  | ||
| Class Example | ||
| Private ReadOnly _logger As ILogger | ||
|  | ||
| Public Sub New(logger As ILogger(Of Example)) | ||
| _logger = logger | ||
| End Sub | ||
|  | ||
| Public Sub ProcessData(data As Integer()) | ||
| ' Fixed: guard with IsEnabled check. | ||
| If _logger.IsEnabled(LogLevel.Debug) Then | ||
| _logger.LogDebug($"Processing {String.Join(", ", data)} items") | ||
| End If | ||
|  | ||
| ' Fixed: guard with IsEnabled check. | ||
| If _logger.IsEnabled(LogLevel.Trace) Then | ||
| _logger.LogTrace("Data: {Data}", New With {.Count = data.Length, .Items = data}) | ||
| End If | ||
| End Sub | ||
| End Class | ||
| ``` | ||
|  | ||
| ## When to suppress warnings | ||
|  | ||
| It's safe to suppress a warning from this rule if performance isn't a concern or if the logging arguments don't involve expensive operations. | ||
|  | ||
| ## Suppress a warning | ||
|  | ||
| If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule. | ||
|  | ||
| ```csharp | ||
| #pragma warning disable CA1873 | ||
| // The code that's violating the rule is on this line. | ||
| #pragma warning restore CA1873 | ||
| ``` | ||
|  | ||
| To disable the rule for a file, folder, or project, set its severity to `none` in the [configuration file](../configuration-files.md). | ||
|  | ||
| ```ini | ||
| [*.{cs,vb}] | ||
| dotnet_diagnostic.CA1873.severity = none | ||
| ``` | ||
|  | ||
| For more information, see [How to suppress code analysis warnings](../suppress-warnings.md). | ||
|  | ||
| ## See also | ||
|  | ||
| - [Performance rules](performance-warnings.md) | ||
| - [High-performance logging in .NET](../../../core/extensions/high-performance-logging.md) | ||
| - [Compile-time logging source generation](../../../core/extensions/logger-message-generator.md) | ||
        
          
  
    
      
          
            122 changes: 122 additions & 0 deletions
          
          122 
        
  docs/fundamentals/code-analysis/quality-rules/ca1874.md
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,122 @@ | ||
| --- | ||
| title: "CA1874: Use 'Regex.IsMatch' (code analysis)" | ||
| description: "Learn about code analysis rule CA1874: Use 'Regex.IsMatch'" | ||
| ms.date: 10/27/2025 | ||
|         
                  gewarren marked this conversation as resolved.
              Show resolved
            Hide resolved | ||
| ms.topic: reference | ||
| f1_keywords: | ||
| - CA1874 | ||
| - UseRegexIsMatchAnalyzer | ||
| helpviewer_keywords: | ||
| - CA1874 | ||
| dev_langs: | ||
| - CSharp | ||
| - VB | ||
|         
                  gewarren marked this conversation as resolved.
              Show resolved
            Hide resolved | ||
| ai-usage: ai-generated | ||
| --- | ||
|  | ||
| # CA1874: Use 'Regex.IsMatch' | ||
|  | ||
| | Property | Value | | ||
| |-------------------------------------|----------------------------------------| | ||
| | **Rule ID** | CA1874 | | ||
| | **Title** | Use `Regex.IsMatch` | | ||
| | **Category** | [Performance](performance-warnings.md) | | ||
| | **Fix is breaking or non-breaking** | Non-breaking | | ||
| | **Enabled by default in .NET 10** | As suggestion | | ||
|  | ||
| ## Cause | ||
|  | ||
| The <xref:System.Text.RegularExpressions.Group.Success> property of the result from <xref:System.Text.RegularExpressions.Regex.Match%2A?displayProperty=nameWithType> is used to check if a pattern matches. | ||
|  | ||
| ## Rule description | ||
|  | ||
| <xref:System.Text.RegularExpressions.Regex.IsMatch*?displayProperty=nameWithType> is simpler and faster than `Regex.Match(...).Success`. The `IsMatch` method is optimized for the case where you only need to know whether a match exists, rather than what the match is. Calling `Match()` and then checking <xref:System.Text.RegularExpressions.Group.Success> does unnecessary work that can impact performance. | ||
|  | ||
| ## How to fix violations | ||
|  | ||
| Replace calls to `Regex.Match(...).Success` with `Regex.IsMatch(...)`. | ||
|  | ||
| A *code fix* that automatically performs this transformation is available. | ||
|  | ||
| ## Example | ||
|  | ||
| The following code snippet shows a violation of CA1874: | ||
|  | ||
| ```csharp | ||
| using System.Text.RegularExpressions; | ||
|  | ||
| class Example | ||
| { | ||
| public bool IsValidEmail(string email) | ||
| { | ||
| // Violation | ||
| return Regex.Match(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$").Success; | ||
| } | ||
| } | ||
| ``` | ||
|  | ||
| ```vb | ||
| Imports System.Text.RegularExpressions | ||
|  | ||
| Class Example | ||
| Public Function IsValidEmail(email As String) As Boolean | ||
| ' Violation | ||
| Return Regex.Match(email, "^[^@\s]+@[^@\s]+\.[^@\s]+$").Success | ||
| End Function | ||
| End Class | ||
| ``` | ||
|  | ||
| The following code snippet fixes the violation: | ||
|  | ||
| ```csharp | ||
| using System.Text.RegularExpressions; | ||
|  | ||
| class Example | ||
| { | ||
| public bool IsValidEmail(string email) | ||
| { | ||
| // Fixed | ||
| return Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$"); | ||
| } | ||
| } | ||
| ``` | ||
|  | ||
| ```vb | ||
| Imports System.Text.RegularExpressions | ||
|  | ||
| Class Example | ||
| Public Function IsValidEmail(email As String) As Boolean | ||
| ' Fixed | ||
| Return Regex.IsMatch(email, "^[^@\s]+@[^@\s]+\.[^@\s]+$") | ||
| End Function | ||
| End Class | ||
| ``` | ||
|  | ||
| ## When to suppress warnings | ||
|  | ||
| It's safe to suppress a warning from this rule if performance isn't a concern. | ||
|  | ||
| ## Suppress a warning | ||
|  | ||
| If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule. | ||
|  | ||
| ```csharp | ||
| #pragma warning disable CA1874 | ||
| // The code that's violating the rule is on this line. | ||
| #pragma warning restore CA1874 | ||
| ``` | ||
|  | ||
| To disable the rule for a file, folder, or project, set its severity to `none` in the [configuration file](../configuration-files.md). | ||
|  | ||
| ```ini | ||
| [*.{cs,vb}] | ||
| dotnet_diagnostic.CA1874.severity = none | ||
| ``` | ||
|  | ||
| For more information, see [How to suppress code analysis warnings](../suppress-warnings.md). | ||
|  | ||
| ## See also | ||
|  | ||
| - [Performance rules](performance-warnings.md) | ||
| - <xref:System.Text.RegularExpressions.Regex.IsMatch%2A?displayProperty=nameWithType> | ||
| - <xref:System.Text.RegularExpressions.Regex.Match%2A?displayProperty=nameWithType> | ||
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.