The console class provides access to the standard input (keyboard), standard output (screen) and standard error (screen) streams. These applications that run in command window.
Write and WriteLine methods
Main features:
· Both methods Console.Write and Console.WriteLine display information on the console
· WriteLine methods append a new line/carriage return pair to the end of the output and write does not append a new line/carriage.
· Both methods are overloaded. We can pass the variable number or types of parameters.
For example
Console.WriteLine("Hello World!");
In this example it shows the message hello world to the screen.
· A format string and parameters can be used
Text Formatting and Numeric Formatting
Formatting means how to show your data on the screen. In text formatting we can use the {0} which means first parameter
For example
int i=12;
Console.WriteLine("Text Formatting: {0} ",i);
Console.WriteLine("fill the spaces 10:{0,10}",i);
Output:
Text Formatting: 12
fill the spaces 10: 12
Note:
Using the backward slash (\) character in a format string to turn off the special meaning of the character that follows it.
For example:
"\{" will cause a literal "{" to be displayed, and "\\" will display a literal "\".
Similar to use the at sign (@) character to represent an entire string verbatim.
For example:
@"\\mind\stick" will be processed as "\\mind\stick."
Numeric Formatting
The format string to specify how numeric data is to be formatted.
The syntax for the format string:
{N,M:FormatString}
Where N is the parameter number,
M is the field width and justification, and
Format String specifies how numeric data should be displayed.
There are some lists the items and its meaning that may appear in
Format String.
· C (Display the number as currency, using the local currency symbol and conventions.)
· D (Display the number as a decimal integer.)
· E (Display the number by using exponential (scientific) notation.)
· F (Display the number as a fixed-point value.)
· G (Display the number as either fixed point or integer, depending on which format is the most compact.)
· N (Display the number with embedded commas.)
· X (Display the number by using hexadecimal notation.)
For example:
Console.WriteLine("Currency formatting - {0:C} {1:C4}", 11.1,-111.1);
Console.WriteLine("Integer formatting - {0:D5}", 11);
Console.WriteLine("Exponential formatting - {0:E}", 111.1);
Console.WriteLine("Fixed-point formatting - {0:F3}",111.1111);
Console.WriteLine("General formatting - {0:G}", 111.1111);
Console.WriteLine("Number formatting - {0:N}", 1111111.1);
Console.WriteLine("Hexadecimal formatting - {0:X4}", 11);
Output:
Currency formatting - $11.10 ($111.1000)
Integer formatting - 00011
Exponential formatting - 1.111000E+002
Fixed-point formatting - 111.111
General formatting - 111.1111
Number formatting - 1,111,111.1
Hexadecimal formatting - 000B
Anonymous User
17-Jun-2019Thanks for sharing the post.
James Smith
06-Aug-2011Nice blog <
Thanks.