Covers topics on the Microsoft Certification Exam for the .NET Framework (Exam 70-536, Microsoft .NET Framework - Application Development Foundation)

Thursday, March 6, 2008

How many strings are allocated in each of the code snippets below?

VisualBasic Code Snippet
Dim s As String

s = "how"
s += " many"
s += " strings"
s += " are"
s += "allocated?"
Console.WriteLine(s)

C# Code Snippet
string s;

s = "how";
s += " many";
s += " strings";
s += " are";
s += "allocated?";
Console.WriteLine(s);


If you said one string was allocated, then... you are wrong. Five strings are actually allocated. Strings in the .NET framework are immutable. This means that each change the string s causes the runtime to create a new string and abandon the old one. The immutable nature of .NET strings should be considered when performance is a concern. The creation of temporary strings can be avoided using two methods:

  • Use the String classes Concat, Join or Format methods to join multiple in a single statement
  • Use the StingBuilder class to create dynamic (mutable) strings

Additional Resources
String class (Microsoft)
StringBuilder class (Microsoft)

No comments:

Support This Site

LinkShare  Referral  Prg