Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do the curly braces mean in C# strings?

while (rdr.Read())
{
    Console.WriteLine("Product: {0,-35} Total: {1,2}", rdr["ProductName"], rdr["Total"]);
}

What does {0,-35} mean in this code?

like image 795
rosebrit3 Avatar asked Mar 19 '12 11:03

rosebrit3


2 Answers

Those brackets are placeholders in strings for values.

So, rdr["ProductName"] will be formatted into the first brackets of the string. And rdr["Total"] will be formatted in the second brackets of the string.

Provided this:

rdr["ProductName"] = "My Product";
rdr["Total"] = 2.98;

Then you will output to the console:

Product: My Product Total: 2.98

After question update:

The {0,-35} part if for alignment purpose. More information on formatting and alignment on C#'s official documentation.

like image 37
Pablo Santa Cruz Avatar answered Sep 30 '22 12:09

Pablo Santa Cruz


A more simple line would be:

Console.WriteLine("{0}", 5);

The function accepts any number of arguments. They will be inserted into the string at the corresponding index. In this case, index zero holds the integer 5. The result is the string "5".

Now, you have the option the specify a format string as well as an index. Like so:

Console.WriteLine("{0:0.00}", 5);

This formats the 5 with 0.00, resulting in 5.00.

Thats the case for numbers, but I think those are more easy to explain. For strings, the "format" implies alignment. Also note that you use a comma rather than a colon to separate index and format.

alignment (optional): This represent the minimal length of the string. Postive values, the string argument will be right justified and if the string is not long enough, the string will be padded with spaces on the left. Negative values, the string argument will be left justied and if the string is not long enough, the string will be padded with spaces on the right. If this value was not specified, we will default to the length of the string argument.

So in your example:

  • {0,-35} means string has to be at least 35 characters, leftjustified (space padding on the end).
  • {1,2} means string has to be at least 2 characters, rightjustified (space padding in front).

I recommend this article, as well as the string.Format documentation.

like image 82
Mizipzor Avatar answered Sep 30 '22 13:09

Mizipzor