Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
Previous Versions
.NET Framework 3.0
Tools
Development Tools
FxCop
FxCop Warnings
 Avoid unnecessary string creation

  Switch on low bandwidth view
This page is specific to
Microsoft Visual Studio 2005/.NET Framework 2.0

Other versions are also available for the following:
Visual Studio Team System
Avoid unnecessary string creation

TypeName

AvoidUnnecessaryStringCreation

CheckId

CA1807

Category

Microsoft.Performance

Breaking Change

NonBreaking

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

A System.String object is immutable. Any change to a string requires creating a new String object. Unnecessary string creation degrades 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 System.String.Equals, System.String.op_Equality(System.String,System.String), or System.String.op_Inequality(System.String,System.String) on a string created by calling ToLower or ToUpper.

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

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, op_Equality, or op_Inequality with a case-insensitive call to System.String.Compare.

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

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

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Preferred use with Switch statement      Adam Brownsea   |   Edit   |   Show History
In regards to the 'Avoid unnecessary string creation' rule, I am trying to determine how to change my code to not break this rule, but not to change my code from a SWITCH statement to an IF statement.

How should the rule be applied to the following code?

string param = "abc";
switch (param.ToUpper())
 {
case "ABC":
// Do abc processing
break;
case "DEF":
// Do def processing
break;
case "GHI":
// Do gei processing
break;
default:
// Do else processing
break;
}


Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker