Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
172 changes: 172 additions & 0 deletions docs/fundamentals/code-analysis/quality-rules/ca1873.md
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
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 docs/fundamentals/code-analysis/quality-rules/ca1874.md
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
ms.topic: reference
f1_keywords:
- CA1874
- UseRegexIsMatchAnalyzer
helpviewer_keywords:
- CA1874
dev_langs:
- CSharp
- VB
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>
Loading