CA1807: Avoid unnecessary string creation

TypeName

AvoidUnnecessaryStringCreation

CheckId

CA1807

Category

Microsoft.Performance

Breaking Change

Non-breaking

Cause

An unnecessary string is created through a call to String.ToLower or String.ToUpper.

Rule Description

A System.String object is immutable. Any change to a string requires the creation of a new String object. Unnecessary string creation decreases performance. This rule flags the following operations that create unnecessary strings:

  1. Multiple calls to ToLower, ToLowerInvariant, ToUpper, or ToUpperInvariant on the same string instance.

  2. Calling String.Equals, String.Equality, or String.Inequality on a string that is created by calling ToLower or ToUpper.

  3. Passing a string that is created by calling ToLower or ToUpper to a member of System.Collections.Specialized.HybridDictionary.

How to Fix Violations

To fix a violation of this rule, eliminate the unnecessary string creation by removing the call to ToLower or ToUpper. The following fixes correspond to the numbering in the Description section:

  1. Assign the result of the first ToLower or ToUpper call to a new variable and use this variable instead of the remaining calls.

  2. Replace the call to Equals, Equality, or Inequality with a case-insensitive call to String.Compare.

  3. Use a case-insensitive HybridDictionary, which is created by passing true as the caseInsensitive argument to the constructor.

When to Suppress Warnings

It is safe to suppress a warning from this rule; however, performance might suffer.

Do not concatenate strings inside loops

CA1820: Test for empty strings using string length