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.
WriteLine() MethodThe 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 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.
Write() MethodIf 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 System;class Program { static void Main() { Console.Write("Hello World! "); Console.Write("I will print on the same line."); } }
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.
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 {}.
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."); } }
What is the difference between Write() and WriteLine()?