Possible Duplicate:
C# String output: format or concat?
what is the benefit of using this:
Console.WriteLine("{0}: {1}", e.Code, e.Reason);
VS. this:
Console.WriteLine(e.Code + ": " + e.Reason);
????
The main advantages of using format(…) are that the string can be a bit easier to produce and read as in particular in the second example, and that we don't have to explicitly convert all non-string variables to strings with str(…).
If you are concatenating a list of strings, then the preferred way is to use join() as it accepts a list of strings and concatenates them and is most readable in this case. If you are looking for performance, append/join is marginally faster there if you are using extremely long strings.
Overview. String formatting uses a process of string interpolation (variable substitution) to evaluate a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.
From a readability standpoint, f-string literals are more aesthetically pleasing and easier to read than string concatenation.
The reason I always use .Format() is for readability and consequently bug reduction and maintenance benefits. Of course this makes no sense if you're relatively new to code as the second example is more intuitive at first. The first appears needlessly complex.
However if you choose the second pattern then you start to have problems when you have lots of variables. This is where it is easier to appreciate the benefits of the first pattern.
e.g
Console.Writeline(var1 + " " + var2 + "-" + var3 +
" some sort of additional text" + var4);
Note the bug: I need another space after "text" but that's not easy to see in this example.
However if I do it the other way:
Console.Writeline("{0} {1}-{2} some sort of additional text{3}",
var1, var2, var3, var4)
It's clearer to see what's going on. Its easier to appreciate the final result when you split the formatting from the variables that are going to be used.
If we want to think even further long term then it helps with globalisation/customisation. If we put those format strings into config we can then change the formatting or ordering of the variables without touching the code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With