Top-level statements, Console and comments
Every example in this handbook is a top-level statements program: the statements at the top of Program.cs run in order, from the first line to the last, and the compiler wraps them in a hidden Main method for you (Getting Started shows the long form). The two methods you will use constantly are Console.WriteLine, which prints and then moves to a new line, and Console.Write, which prints and stays on the same line.
// A single-line comment: the compiler ignores it
Console.WriteLine("Order summary");
Console.Write("Items: "); // no newline after this
Console.WriteLine(3);
Console.WriteLine(); // an empty line
/* A block comment can
span several lines */
Console.WriteLine("Total: " + 42.5);
Console.WriteLine("Tab\tseparated and a \"quote\"");Order summary
Items: 3
Total: 42.5
Tab separated and a "quote"Print your name and city on one line using one Console.Write and one Console.WriteLine.
Console.ReadLine() reads one line the user typed and returns it as a string, without the Enter key. It returns null when there is no more input (for example, when input is piped from a file that has ended), so the type is string?. The program below reads two lines; the input it was run with is shown under the code.
Console.Write("Name: ");
string? name = Console.ReadLine();
Console.Write("Age: ");
string? ageText = Console.ReadLine();
int age = int.Parse(ageText ?? "0"); // text -> number
Console.WriteLine();
Console.WriteLine($"Hello, {name}. Next year you will be {age + 1}.");Name: Age:
Hello, Ada. Next year you will be 37.Typed input is not echoed to stdout when it is piped in, which is why the prompts run together here. In a terminal you would see what you type after each prompt.
Ask for a second number and print the sum of the two.
// runs to the end of the line. /* ... */ spans lines. /// is an XML documentation comment placed above a type or method; IDEs show it on hover and the build can export it. Write comments that say why the code does something — the code already says what.