C#, lesson 1
Every program needs a way to show you what it is doing. In C# you write text to the screen with
Console.WriteLine. It prints the value you give it and then moves to a new line.
That is a complete C# program. The first line, using System;, tells the compiler where to find
Console: it lives in the System namespace, a named group of related types. A full .NET
project template adds common using lines for you behind the scenes, but the runner in this
course compiles a single plain file, so you write them yourself at the very top. Each statement ends with a semicolon ;. Text in double
quotes is a string. A single character such as 'A' uses single quotes and is a different
type, so for text always use double quotes.
2 exercises to try what you just read.
Older C# programs wrap everything in a class Program with a static void Main() method. Since
C# 9 you can skip that ceremony and write statements straight into the file. These are called
top-level statements, and the compiler builds the hidden Main method for you. Every lesson in
this course uses this modern style. Later, when you write your own types, they go below the
top-level statements in the same file.
Console.Write prints without the new line, so the next output continues on the same line:
You can glue text and numbers together with +, but C# has a nicer tool called string
interpolation. Put a $ before the opening quote and drop any expression inside { }:
The compiler ignores comments. They are notes for the people who read your code.
C# is a compiled language. Before anything runs, the compiler reads the whole file and checks
it. If you forget a semicolon or misspell Console, nothing runs at all and you get a compile
error with a line number and an error code such as CS1002. Read the message carefully; it
usually points straight at the problem. Once the code compiles, the statements run in order, top
to bottom.
Names in C# are case sensitive: Console.WriteLine works, console.writeline does not.
Write a program that prints exactly these two lines:
The program reads no input.
Print a rocket countdown. Use Console.Write for 3... , 2... and 1... (each followed by a
space) and then Console.WriteLine for Liftoff!, so all of it ends up on one line. On the next
line, print Fuel: 75% using string interpolation with a variable int fuel = 75;.
Expected output:
using System;
Console.WriteLine("Hello, World!");
Console.WriteLine("C# runs one statement at a time, from top to bottom.");Console.Write("Loading");
Console.Write("...");
Console.WriteLine("done"); // Loading...doneint apples = 3;
Console.WriteLine("Apples: " + apples); // Apples: 3
Console.WriteLine($"Apples: {apples}"); // Apples: 3
Console.WriteLine($"Double: {apples * 2}"); // Double: 6// A single-line comment runs to the end of the line.
Console.WriteLine("This runs"); // a comment can follow code
/* A block comment
can span several lines. */Hello, World!
I am learning C#.3... 2... 1... Liftoff!
Fuel: 75%