แก้ไข

แชร์ผ่าน


CA1859: Use concrete types when possible for improved performance

Property Value
Rule ID CA1859
Title Use concrete types when possible for improved performance
Category Performance
Fix is breaking or non-breaking Non-breaking
Introduced version .NET 8
Enabled by default in .NET 9 As suggestion

Cause

Code uses interface types or abstract types, leading to unnecessary interface calls or virtual calls.

Rule description

This rule recommends upgrading the type of specific local variables, fields, properties, method parameters, and method return types from interface or abstract types to concrete types when possible. Using concrete types leads to higher quality generated code by minimizing virtual or interface dispatch overhead and enabling inlining.

This rule only reports violations when there are virtual calls or interface calls that can actually be avoided by using a concrete type.

How to fix violations

Upgrade the types as recommended by the rule. In general, changing the type has no effect on the behavior of the code, but it improves its performance.

Example

The following code snippet shows a violation of CA1859:

abstract class A
{
    public virtual void M() { }
}

sealed class B : A
{ }

internal class C
{
    private readonly A _a = new B();

    public void Trigger()
    {
        // This performs a virtual call because
        // _a is defined as an abstract class.
        _a.M();
    }
}

The following code snippet fixes the violation:

abstract class A
{
    public virtual void M() { }
}

sealed class B : A
{ }

internal class C
{
    private readonly B _b = new B();

    public void Trigger()
    {
        _b.M();
    }
}

When to suppress warnings

It's safe to suppress a warning 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.

#pragma warning disable CA1859
// The code that's violating the rule is on this line.
#pragma warning restore CA1859

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.CA1859.severity = none

For more information, see How to suppress code analysis warnings.