Quote:Original post by RJSnow
On the side, I'm reading a different C# book, I know this isn't in the specification, but it has to deal with C#, so maybe someone can answer this.
What's the real difference between these two styles? Is one style better than the other?Quote:
Console.WriteLine("Hello, {0}!", FirstName);
andQuote:
Console.WriteLine("Hello, "+FirstName+" !");
It is usually better to use the first one. Using the + operator on strings builds a completely new string, because in C# strings are immutable (ie. they cannot be changed), so a new one needs to be built, and can result in reduced performance for larger strings.
In fact, the StringBuilder class is the preferred method of combining strings, as it doesn't have to create and destroy strings in memory when it is used. If you are wondering when to use these three different methods ( +operator, {0}, and StringBuilder), consider the following points:
1) It's much easier to see in the code the + operator, and it is more intuitive for quick read-throughs. For this reason, I almost always use the + operator, even though it is slightly less efficient, because the difference is rather small for most operations. After I profile my code, I can see if I need to go back and change it.
2) The format method used by Console.WriteLine and string.Format actually use a StringBuilder internally, so calling the Console.WriteLine in the first example is actually the same as using a StringBuilder. Hence the reason that the first example is "better".
Hope it all helps!