In C# when we want to print any data to output in Console application, we use Console.WriteLine()
or Console.Write()
methods, let's understand each of these in more details one by one.
Console.WriteLine() Method is used to print data in standard output stream, it also makes control move to the next line.
public static void WriteLine ();
Console.WriteLine()
method has total 19 overloaded methods, here are the few methods:
For Complete List, refer https://docs.microsoft.com/en-us/dotnet/api/system.console.writeline?view=netframework-4.8
Let's take a look at sample C# Console Applications which prints output using Console.WriteLine()
using System;
public class BasicIO
{
public static void Main()
{
//string array containing lines
string[] lines = { "This is the first line.",
"This is the second line." };
// Output the lines using the default newline sequence.
Console.WriteLine("With the default new line characters:");
//add a line break
Console.WriteLine();
//loop through each line using foreach loop
foreach (string line in lines)
{
Console.WriteLine(line);
}
Console.WriteLine();
}
}
Output:
With the default new line characters:
This is the first line.
This is the second line.
In the above example, we are first creating a string array lines
, and looping it using foreach
loop, then printing array values using Console.WriteLine(String)
method to print string value from array one by one and moving cursor to next line.
Console.Write()
method is similar to Console.WriteLine()
, except one thing it doesn't move cursor to next line, basically it writes the text representation of the specified value or values to the standard output stream.
It has total 18 overloaded methods, widely used one's are Console.Write()
, Console.Write(String)
and Console.Write(Int 32)
.
Let's take a look at sample C# Console Applications which prints output using Console.Write()
We will be using same example, as used with Console.WriteLine() but this time instead of using Console.WriteLine() we will use Console.Write().
using System;
public class BasicIOProgram
{
public static void Main()
{
//string array containing lines
string[] lines = { "This is the first line.",
"This is the second line." };
// Output the lines using the default newline sequence.
Console.Write("With the default new line characters:");
//add a line break
Console.WriteLine();
//loop through each line using foreach loop
foreach (string line in lines)
{
Console.Write(line);
}
Console.Write();
}
}
Output.
With the default new line characters:
This is the first line.This is the second line.
As you can see, in the above example, we didn't used WriteLine
and used Write
inside the loop, because of which it printed both string line value in same line.