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:

  1. Print out content of string type.
string name = "John";
Console.WriteLine("My name is " + name);
  1. Output content in the form of numerical values.
int age = 25;
Console.WriteLine("I am " + age + " years old");
  1. 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}");
  1. 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.

广告
Closing in 10 seconds
bannerAds