Mark
Mark

Reputation: 3123

Displaying text syntax, two different methods, which is better and why?

What is the advantages between the syntax in C# (or other programmign languages) to displaying text in an application.

decimal fooTotal = 2.53;

For example:

Console.WriteLine("Filtered total: {0:c}", fooTotal);

VS

Console.WriteLine("Filtered total: " + fooTotal);

I see the first method in more examples and books (Current the MVC 3 book I'm going through) but I was taught method 2. I could hypothesize that method one would allow you to change values quickly? The first value would also be displayed in currency which I"m also assuming is more succinct ?

Upvotes: 1

Views: 92

Answers (3)

Amittai Shapira
Amittai Shapira

Reputation: 3827

String.Format() is also better in localization scenarios, where you take the string out of StringTable, and the parameters (which you don't know where and in what order they'll appear in the string) from your code.

Upvotes: 0

BrokenGlass
BrokenGlass

Reputation: 160922

I personally prefer the string.Format() / first shown alternative almost always. Biggest advantage is that it allows you to separate how you want to print an argument - the text presentation - from the data, the argument itself. The more variables you have to print the cleaner this looks (to me) compared to the string concatenation alternative.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1501163

The first form applies the c format specifier to the value, which treats it as a currency. To change the second snippet to behave similarly, you could use:

Console.WriteLine("Filtered total: " + fooTotal.ToString("c"));

I'll often use string concatenation (the second form) for just a single parameter, but when I've got multiple values to include or I want to specify a format specifier, I'll use string.Format or the equivalent. (Console.WriteLine effectively calls string.Format for you here.)

Upvotes: 2

Related Questions