Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to print a line on the console using C#?
To display a line on the console in C#, we use the Console.WriteLine() method. This method prints text to the console and automatically adds a new line at the end.
Syntax
Following is the syntax for printing a line to the console −
Console.WriteLine(value);
Where value can be a string, variable, or any expression that can be converted to a string.
Using Console.WriteLine() with Strings
The most common use is to print string literals or string variables −
using System;
public class Program {
public static void Main() {
string str = "Tom Hanks is an actor";
Console.WriteLine("Displaying a line below");
Console.WriteLine(str);
}
}
The output of the above code is −
Displaying a line below Tom Hanks is an actor
Using Console.WriteLine() with Different Data Types
The Console.WriteLine() method can print various data types directly −
using System;
public class Program {
public static void Main() {
int age = 65;
double salary = 45000.75;
bool isActive = true;
Console.WriteLine("Age: " + age);
Console.WriteLine("Salary: " + salary);
Console.WriteLine("Active: " + isActive);
}
}
The output of the above code is −
Age: 65 Salary: 45000.75 Active: True
Console.WriteLine() vs Console.Write()
The difference between Console.WriteLine() and Console.Write() is that WriteLine() adds a new line after printing, while Write() does not −
using System;
public class Program {
public static void Main() {
Console.Write("Hello ");
Console.Write("World!");
Console.WriteLine();
Console.WriteLine("Next line starts here");
}
}
The output of the above code is −
Hello World! Next line starts here
Comparison of Console Output Methods
| Method | Description | Adds New Line |
|---|---|---|
Console.WriteLine() |
Prints text and moves cursor to next line | Yes |
Console.Write() |
Prints text and keeps cursor on same line | No |
Conclusion
The Console.WriteLine() method is the primary way to print lines to the console in C#. It automatically adds a new line after the output, making it perfect for displaying text that should appear on separate lines. Use Console.Write() when you want to print multiple items on the same line.
