Console.Write syntax: what does the format string "{0, -25}" mean

I am writing C# code

Console.Write("{0,-25}", company); 

In above code what does this "{0,-25}" thing mean?

1

5 Answers

You mention it's hard to see what it does: that's because it adds spaces and those are difficult to see in the console. Try adding a character directly before and after the output so you can more clearly see the space, like the examples below:

This

Console.WriteLine("[{0, -25}]", "Microsoft"); // Left aligned Console.WriteLine("[{0, 25}]", "Microsoft"); // Right aligned Console.WriteLine("[{0, 5}]", "Microsoft"); // Ignored, Microsoft is longer than 5 chars 

Will result in this (with spaces)

[Microsoft ] [ Microsoft] [Microsoft] 

Which looks like this in the console window:

enter image description here

Read about string formatting on MSDN, specifically composite formatting. The '-25;' specifies the alignment component.

Alignment Component The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.

That 'thing' is a composite formatting string. See the remarks here and this article here.

It is used for alignment.
Check this so that you can get

Console.Write("Company = |{0,-25}|", company); 
string company1="ABC Inc"; string company2="XYZ International Inc"; Console.Write("{0,-10}", company1);//o/p [ABC Inc...] Console.Write("{0,10}", company1);o/p [...ABC Inc] Console.Write("{0,-10}", company2);o/p [XYZ International Inc] 

//In the first Write(),output is LEFT justified in an output field width of 10

//In second Write(), output is RIGHT justified in an output field width of 10

//In the third Write(), output width is ignored , since the company2 name has more than 10 characters.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like