C#idiomatic C#
ca1514fundamentals/code-analysis/quality-rules

Code analysis

CA1514: Avoid redundant length argument

Learn about code analyzer rule CA1514 - Avoid redundant length argument

CA1514 Maintainability enabled by default in .NET 10: As suggestion
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

A redundant length argument is passed to System.String.Substring, System.Span.Slice, System.ReadOnlySpan.Slice, or System.Memory.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:

csharp
string message = "Hello World!";
string world = message.Substring(6, message.Length - 6); // "World!"
vb
Dim message As String = "Hello World!"
Dim world As String = message.Substring(6, message.Length - 6) ' "World!"

The following code snippet fixes the violation:

csharp
string message = "Hello World!";
string world = message.Substring(6); // "World!"
vb
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.

csharp
#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.

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

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