Why use String.Concat() in C#?
I myself have been having this same question and this question triggered me to investigate into it a bit,
I created the following class
public class Class1
{
string str = "One" + "Team";
string str2 = string.Concat("One", "Team");
}
And below is corresponding IL code for that.
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 40 (0x28)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldstr "OneTeam"
IL_0006: stfld string StringConcat.Class1::str
IL_000b: ldarg.0
IL_000c: ldstr "One"
IL_0011: ldstr "Team"
IL_0016: call string [mscorlib]System.String::Concat(string, string)
IL_001b: stfld string StringConcat.Class1::str2
IL_0020: ldarg.0
IL_0021: call instance void [mscorlib]System.Object::.ctor()
IL_0026: nop
IL_0027: ret
// end of method Class1::.ctor
}
For me it definitely looks like string.Concat
is having more steps than overloaded + operator. But I know for sure inside the System.String
class there will be similar set of operations happening for overloaded + operator as well. Thoughts?
Because you can use the version that takes two objects ;)
As long as the two operands are strings, there is no difference at all between using the +
operator and the String.Concat
method. The code using the +
operator actually compiles into a String.Concat
call.
Use the one that best represents your intention with the code.
I use +
when I know how many strings are going to be concatenated - but what if you just have an array? In that case you wouldn't know how many times to apply +
, so you'd have to call a method (or loop yourself, which is horrible).
I can't remember calling string.Concat
very often though - it's a definite rarity.
As guffa says, +
compiles down into calls to string.Concat
anyway - it's worth being aware that string
doesn't actually have a + operator, which can be a cause of confusion if you ever try to use it in reflection!
One benefit of +
though is that if all the arguments are constant expressions, the compiler will perform the concatenation for you, so you don't need to do it at execution time. That sort of tiny performance benefit isn't going to be significant in most code, but it's always nice when the code I find most readable also has a performance advantage :)