O'Reilly logo

Programming C# 4.0 by Jesse Liberty, Matthew Adams, Ian Griffiths

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Composing Strings

You can create a new string by composing one or more other strings. Example 10-55 shows one way to do this.

Example 10-55. Concatenating strings

string fragment1 = "To be, ";
string fragment2 = "or not to be.";
string composedString = fragment1 + fragment2;
Console.WriteLine(composedString);

Here, we’ve used the + operator to concatenate two strings. The C# compiler turns this into a call to the String class’s static method Concat, so Example 10-56 shows the equivalent code.

Example 10-56. Calling String.Concat explicitly

string composedString2 = String.Concat(fragment1, fragment2);
Console.WriteLine(composedString2);

Note

Don’t forget—we’re taking the first two strings, and then creating a new string that is fragment1.Length + fragment2.Length characters long. The original strings remain unchanged.

There are several overloads of Concat, all taking various numbers of strings—this enables you to concatenate multiple strings in a single step without producing intermediate strings. One of the overloads, used in Example 10-57, can concatenate an entire array of strings.

Example 10-57. Concatenating an array of strings

static void Main(string[] args) { string[] strings = Soliloquize(); string output = String.Concat(strings); Console.WriteLine(output); Console.ReadKey(); } private static string[] Soliloquize() { return new string[] { "To be, or not to be--that is the question:", "Whether 'tis nobler in the mind to suffer", "The slings and arrows of outrageous fortune", "Or to ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required