🆚 Console.WriteLine() vs Console.Write() in C#
In C#, both Console.WriteLine()
and Console.Write()
are used to output text to the console. However, they behave slightly differently in terms of formatting. Let’s explore their differences with examples and output.
📘 1. Console.WriteLine()
Console.WriteLine() prints the text followed by a **newline character**. It moves the cursor to the next line after displaying the content.
📘 2. Console.Write()
Console.Write() prints the text **without moving to a new line**. It keeps the cursor on the same line, allowing you to continue outputting content on the same line.
📄 C# Example Code
using System;
class Program
{
static void Main()
{
Console.WriteLine("This is using WriteLine()");
Console.WriteLine("Line breaks after each message.");
Console.Write("This is ");
Console.Write("using ");
Console.Write("Write()");
Console.Write(".");
}
}
📝 Sample Output
This is using WriteLine()
Line breaks after each message.
This is using Write().
Line breaks after each message.
This is using Write().
🔍 Key Differences
- WriteLine(): Appends a newline after writing the string.
- Write(): Continues on the same line after writing the string.
- Use Write() when you want to build text on the same line (e.g., progress bars, inline output).
- Use WriteLine() for standard output with each message on a new line.
✅ Summary Table
Feature | Console.Write() | Console.WriteLine() |
---|---|---|
Adds newline? | No | Yes |
Cursor stays on same line? | Yes | No |
Common use | Inline output | Formatted output |
Post a Comment