How do you use Console.WriteLine() in C#?
Console.WriteLine() is a method in C# used for printing output. It can take one or more parameters and display them on the console window.
Below are some examples of using the Console.WriteLine() method:
- Print out content of string type.
string name = "John";
Console.WriteLine("My name is " + name);
- Output content in the form of numerical values.
int age = 25;
Console.WriteLine("I am " + age + " years old");
- Outputting multiple parameters:
string firstName = "John";
string lastName = "Doe";
Console.WriteLine("My name is {0} {1}", firstName, lastName);
Alternatively, you could use string interpolation.
string firstName = "John";
string lastName = "Doe";
Console.WriteLine($"My name is {firstName} {lastName}");
- Output formatted string:
int number = 42;
Console.WriteLine("The answer to the ultimate question of life, the universe, and everything is {0:D}", number);
The method Console.WriteLine() in the above example will display the contents of the parameter in the console window and automatically create a new line.