C# Output

C# Output: Printing to the Screen

In C#, communicating with the user often starts with outputting text or data to the console. The Console class (which is part of the System namespace) provides the methods we need to display information.


1. The WriteLine() Method

The most common method to output text is Console.WriteLine(). This method prints the text you provide and then automatically adds a new line (like pressing "Enter" on your keyboard) at the end.

Using WriteLine()

using System;

class Program { static void Main() { Console.WriteLine("Hello World!"); Console.WriteLine("I am learning C#."); Console.WriteLine("It is awesome!"); } }

Notice how each sentence in the output above will appear on a separate line.


2. The Write() Method

If you want to output text without adding a new line at the end, you use the Console.Write() method. Any subsequent output will be printed on the same line.

Using Write()

using System;

class Program { static void Main() { Console.Write("Hello World! "); Console.Write("I will print on the same line."); } }


Outputting Numbers and Math

You can also use these methods to output numbers, and you can even perform mathematical calculations directly inside them. Note that when outputting numbers, you do not put them in quotes.

Outputting Variables and Formatting

You can output variables by simply placing the variable name inside the WriteLine() method. To combine text and variables, you can use the + operator.

However, C# also offers a much cleaner way to format output called String Interpolation. By placing a $ symbol before the string, you can insert variables directly inside curly braces {}.

String Interpolation

using System;

class Program { static void Main() { string name = "John"; int age = 28; // Using string interpolation Console.WriteLine($"My name is {name} and I am {age} years old."); } }


Exercise

?

What is the difference between Write() and WriteLine()?