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
What is the difference between Write() and WriteLine() methods in C#?
The difference between Write() and WriteLine() methods in C# is based on the new line character. Both methods are used to display output to the console, but they handle line termination differently.
Write() method displays the output but does not provide a new line character, so subsequent output appears on the same line. WriteLine() method displays the output and automatically adds a new line character at the end, moving the cursor to the next line for subsequent output.
Syntax
Following is the syntax for Write() method −
Console.Write(value);
Console.Write("text");
Following is the syntax for WriteLine() method −
Console.WriteLine(value);
Console.WriteLine("text");
Using Write() Method
The Write() method outputs text without adding a line break, keeping all output on the same line −
Example
using System;
class Program {
static void Main() {
Console.Write("Hello");
Console.Write(" ");
Console.Write("World");
Console.Write("!");
}
}
The output of the above code is −
Hello World!
Using WriteLine() Method
The WriteLine() method outputs text and automatically moves to the next line −
Example
using System;
class Program {
static void Main() {
Console.WriteLine("First line");
Console.WriteLine("Second line");
Console.WriteLine("Third line");
}
}
The output of the above code is −
First line Second line Third line
Comparison of Write() and WriteLine()
This example demonstrates the key difference between both methods −
Example
using System;
class Program {
static void Main() {
Console.Write("One");
Console.Write("Two");
// this will set a new line for the next output
Console.WriteLine("Three");
Console.WriteLine("Four");
// mixing both methods
Console.Write("Start ");
Console.WriteLine("End");
Console.Write("Next");
}
}
The output of the above code is −
OneTwoThree Four Start End Next
Comparison Table
| Write() Method | WriteLine() Method |
|---|---|
| Outputs text without a new line character | Outputs text with a new line character at the end |
| Cursor remains on the same line | Cursor moves to the next line |
| Subsequent output continues on same line | Subsequent output starts on new line |
| Useful for building output incrementally | Useful for displaying complete lines |
Conclusion
The Write() method outputs text without line breaks, while WriteLine() automatically adds a new line after the output. Choose Write() when you want to build output on the same line, and WriteLine() when you want each output on a separate line.
