Jan 14, 2008

How to write quality code? Tip1, StringOperations

  1. Use StringBuilder instead of string variable in case of concatenations.

C# Code (Wrong)

C# Code (Correct)

String xXml = “”;
for(Int32 nRep = 1; nRep<=Reps; nRep++ )
{
sXml += "<Order orderId=""
+ nRep
+ "" orderDate=""
+ DateTime.Now.ToString()
+ "" customerId=""
+ nRep
}

// make sure that the StringBuilder capacity is large enough for the resulting text
StringBuilder oSB = new StringBuilder(165);
for (Int32 nRep = 1; nRep <= Reps; nRep++)
{
oSB.Append("<Order orderId="");
oSB.Append(nRep);
oSB.Append("" orderDate="");
oSB.Append(DateTime.Now.ToString());
oSB.Append("" customerId="");
oSB.Append(nRep);
}

Note:

  • Use + When the Number of Appends Is Known or Fixed (String str = str1+str2+str3)
  • The StringBuilder class starts with a default initial capacity of 16. Strings less than the initial capacity are stored in the StringBuilder object.

  1. Use the Overloaded Compare Method for Case-Insensitive String Comparisons as shown below.

C# Code (Wrong)

C# Code (Correct)

// Bad way for insensitive operations because ToLower creates temporary strings
String str="New York";
String str2 = "New york";
if (str.ToLower()==str2.ToLower())
// do something

str.Compare(str, str2, false);

Useful links on string:-

No comments: