How to Use Console.WriteLine in C# for Output
Use
Console.WriteLine in C# to print text or variables to the console. It writes the specified message followed by a new line, making it easy to display output during program execution.Syntax
The basic syntax of Console.WriteLine is simple. You call it with the message or value you want to display inside parentheses and quotes if it is text.
- Console: The class that handles console input and output.
- WriteLine: The method that prints the message and moves to the next line.
- "message": The text or variable you want to show.
csharp
Console.WriteLine("Your message here");Example
This example shows how to print a simple text message and a variable value using Console.WriteLine.
csharp
using System; class Program { static void Main() { string name = "Alice"; Console.WriteLine("Hello, World!"); Console.WriteLine("Welcome, " + name + "!"); } }
Output
Hello, World!
Welcome, Alice!
Common Pitfalls
Some common mistakes when using Console.WriteLine include:
- Forgetting quotes around text, which causes errors.
- Using
Console.WriteLinewithout parentheses. - Trying to print variables without converting them to string or concatenating properly.
Here is an example of a wrong and right way:
csharp
// Wrong: Missing quotes around text // Console.WriteLine(Hello World); // Right: Text inside quotes Console.WriteLine("Hello World");
Quick Reference
Tips for using Console.WriteLine:
- Use
+""+to join text and variables. - Use
Console.Writeif you don't want a new line after output. - Use string interpolation for cleaner code:
$"Hello, {name}!".
Key Takeaways
Console.WriteLine prints text or variables to the console with a new line.
Always put text inside quotes and use parentheses when calling Console.WriteLine.
Use + or string interpolation to combine text and variables easily.
Console.WriteLine helps you see output during program execution for debugging or interaction.