Code uses interface types or abstract types, leading to unnecessary interface calls or virtual calls.
Rule descriptionThis 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 violationsUpgrade 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.
ExampleThe 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 warningIf 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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4