
Best Practices for String Processing
• Always prefer a char (C#) or Char (VB 2005) data type when you are only storing an individual
character.
• System.Char is more efficient as it is a value type not a heap allocated System.String.
• By default, string member variables are assigned to the value of null (C#) or Nothing (VB).
• Always assign string member variables to zero length strings (or String.Empty) at the time of
declaration.
• This has no ill effect of memory consumption.
• If you do not, the caller will need to test for a null value, and may possibly trip a
NullReferenceException.
// C#
class MyClassType
{
private string mFirstName = "";
private string mLastName = "";
private string mSSN = String.Empty;
...
}
' VB 2005
Class MyClassType
Private mFirstName As String = ""
Private string mLastName As String = ""
Private string mSSN As String = String.Empty
...
End Class
• When checking if a string is empty, always check the Length property for the value zero.
• This is much faster than checking a string for the value "" or String.Empty.
• When concatenating fixed length string data, always prefer the string.Format() method rather than your
languages concatenation symbol.
• The removes the need to convert numerical data to string representations.
• This also allows you to format the data via the .NET string formatting tokens.
• It is ultimately more efficient as well, as it can reduce the amount of string objects which are allocated
on the heap.
// C#
public void SomeMethod()
{
string s = "Hello";
// Bad!
string s2 = s + " world!";
// Good!
string s3 = string.Format("Hello {0}", s);
}
' VB 2005
Public Sub SomeMethod()
Dim s As string = "Hello"
' Bad!
Dim s2 As String = s & " world!"
' Good!
Dim s3 As String = String.Format("Hello {0}", s)
End Sub
• When concatenating variable length string data, prefer the System.Text.StringBuilder type.
• This type allows you to specify the initial size of the underlying buffer via a constructor parameter.
• If a StringBuilder’s buffer grows longer than the initial size, a new StringBuilder is created, the old
buffer is copied into the object and the buffer grows by the originally specified size.
• The default buffer size is a meager 16 characters, so get in the habit of defining an initial size to decrease
the number of copies / wasted buffer space.
// C#
// Create a builder with 256 chars.
StringBuilder sb = new StringBuilder(256);
' VB 2005
' Create a builder with 256 chars.
Dim sb As New StringBuilder(256)
• As well, this type provides the Append() and AppendFormat() methods to append to this buffer.
• Don’t create temporary string variables simply to add them to the StringBuilder object. It defeats the
whole purpose!
String Processing
Table of Contents
Copyright (c) 2008. Intertech, Inc. All Rights Reserved. This information is to be used exclusively as an
online learning aid. Any attempts to copy, reproduce, or use for training is strictly prohibited.
Courseware
Training Resources
Tutorials