Use concrete types when possible for improved performance
Use concrete types when possible for improved performance
Microsoft docsDescription
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.
Cause
Code uses interface types or abstract types, leading to unnecessary interface calls or virtual calls.
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
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();
}
}
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
It's safe to suppress a warning if performance isn't a concern.