CA1863: Use 'CompositeFormat'
Property | Value |
---|---|
Rule ID | CA1863 |
Title | Use CompositeFormat |
Category | Performance |
Fix is breaking or non-breaking | Non-breaking |
Enabled by default in .NET 9 | No |
Cause
Code calls String.Format(String, Object[]) or StringBuilder.AppendFormat(String, Object[]) with a static
format string that hasn't been cached to a CompositeFormat instance.
Rule description
It's expensive to parse a format string at run time. This rule locates places in your code where you can cache and use a CompositeFormat instance as the argument to a formatting operation, rather than passing in the original format string. A CompositeFormat instance parses the composite format string when it's created, which means the "hot path" of string formatting can execute much faster.
How to fix violations
Create an instance of CompositeFormat by calling CompositeFormat.Parse(String) and pass it to String.Format(IFormatProvider, CompositeFormat, Object[]) or StringBuilder.AppendFormat(IFormatProvider, CompositeFormat, Object[]) instead of the original format string.
Example
The following example shows two violations of the rule:
class C
{
private static readonly string StaticField = "Format one value: {0}";
static void Main()
{
_ = string.Format(StaticField, 42);
StringBuilder sb = new();
sb.AppendFormat(StaticField, 42);
}
}
The following example shows code that fixes both violations:
class C
{
private static readonly CompositeFormat StaticField = CompositeFormat.Parse("Format one value: {0}");
static void Main()
{
_ = string.Format(null, StaticField, 42);
StringBuilder sb = new();
sb.AppendFormat(null, StaticField, 42);
}
}
When to suppress warnings
It's safe to suppress diagnostics 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.
#pragma warning disable CA1863
// The code that's violating the rule is on this line.
#pragma warning restore CA1863
To disable the rule for a file, folder, or project, set its severity to none
in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA1863.severity = none
For more information, see How to suppress code analysis warnings.