CA1514: Avoid redundant length argument
Property | Value |
---|---|
Rule ID | CA1514 |
Title | Avoid redundant length argument |
Category | Maintainability |
Fix is breaking or non-breaking | Non-breaking |
Enabled by default in .NET 9 | As suggestion |
Cause
A redundant length argument is passed to String.Substring, Span<T>.Slice, ReadOnlySpan<T>.Slice, or Memory<T>.Slice when slicing to the end of a string or buffer.
Rule description
An explicitly calculated length argument can be error-prone and is unnecessary when you're slicing to the end of a string or buffer.
Code that omits the length argument is more readable and maintainable.
How to fix violations
Remove the length argument.
Example
The following code snippet shows a violation of CA1514:
string message = "Hello World!";
string world = message.Substring(6, message.Length - 6); // "World!"
Dim message As String = "Hello World!"
Dim world As String = message.Substring(6, message.Length - 6) ' "World!"
The following code snippet fixes the violation:
string message = "Hello World!";
string world = message.Substring(6); // "World!"
Dim message As String = "Hello World!"
Dim world As String = message.Substring(6) ' "World!"
When to suppress warnings
It's safe to suppress a violation of this rule if you're not concerned about the maintainability of your code.
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 CA1514
// The code that's violating the rule is on this line.
#pragma warning restore CA1514
To disable the rule for a file, folder, or project, set its severity to none
in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA1514.severity = none
For more information, see How to suppress code analysis warnings.