Wednesday, March 9, 2011

KnowDotNet: String.Concat() and string contatenation

String.Concat() allows you to pass in multiple strings and it will create a new string big enough to contain the individual strings that you pass into the function. It then copies the individual strings into the new bigger strings.

So if you go like this:
using System;

class Tests
{
    static void Main( string [] args ) {
        string str1 = "This is a number: ";
        string str2 = 55.ToString();

        string newString = String.Concat( str1, str2 );
        Console.WriteLine( newString );
    }
}
You will get:
This is a number: 55
If you change the line that declares the newString variable to this:
string newString = str1 + str2;
The the IL code that is generated is exactly the same. String concatenation like that above is replaced by the compiler as a call to String.Concat(). In other words, the first example is fine; it just requires more typing. For more information on some of the interesting aspects of string concatenation then read this article called "Concatenating Strings Efficiently".

String.Concat() for Arrays of Strings.
Other String.Concat() overloads allows passing a string array as an argument. You can even pass arrays of objects; each on will have .ToString() called and the results concatenated.

using System;

class Tests
{
    static void Main( string [] args ) {
        string [] items = { "String1", "String2", "String3" };

        string newString = String.Concat( items );
        Console.WriteLine( newString );
    }
}

No comments:

Post a Comment