0
        int n=6;
        string a=null;
        for(int i=0;i<=n;i++){
            Console.WriteLine("{0,"+n+"}",a+="#");
        }

Any one can explain what it (+n+) actually doing in this code? Why it's not printing the value of n instead spaces.

I am new and i'm learning c#.

Siam
  • 1
  • 1
  • 2
    String concatenation + old formatting style. – Jimi Jun 03 '22 at 14:12
  • It concatinates the number n into the string. + [Composite formatting](https://learn.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting), specifically [Alignment Component](https://learn.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting#alignment-component) – Fildor Jun 03 '22 at 14:12
  • 1
    why not just try it out by debugging? – MakePeaceGreatAgain Jun 03 '22 at 14:12
  • `Console.WriteLine("{0,5}", "#");` prints `" #"` This code is putting the value of `n` where I have a `5`. – 001 Jun 03 '22 at 14:13
  • Also see the [Control Spacing](https://learn.microsoft.com/en-us/dotnet/api/system.string.format?view=net-6.0#control-spacing) documentation for string formatting. – Matthew Watson Jun 03 '22 at 14:29
  • 1
    The "duplicate" is talking about string concatenation, but this question is really about string formatting. – Matthew Watson Jun 03 '22 at 14:43
  • Ah, and the _reason_ why concatenation is used is that the author obviously wanted to change only one single place in the code to scale the output. – Fildor Jun 03 '22 at 15:22

1 Answers1

0

The expression:

"{0,"+n+"}"

Can be divided into few parts:

"{0," is a string literal. It's a string containing 3 characters: the bracket, the zero and the comma.

+n appends the current value of the int variable n to the previous string.

+"}" appends a string literal "}" (a string with only one character, the bracket) to the previous string.

For example, if n equals 6, then the expression will produce a {0,6} string.

Orion
  • 566
  • 4
  • 9