Console.WriteLine
Learn to print text and variables to the screen with Console.WriteLine.
The dotnet run command
The easiest way to run a C# program is the dotnet run command. It first compiles your code, then runs it.
In a terminal, you go to the project folder and type:
dotnet runThe command shows the output in the terminal. If there are errors, they are listed here.
dotnet is the main command that ships with the .NET SDK; subcommands manage the project.
IL code and the CLR
C# code is not compiled directly to machine code; it is first compiled to an intermediate code called IL (Intermediate Language).
When the program runs, the CLR (Common Language Runtime) takes this IL code, translates it to machine code and executes it.
This two-step design lets C# run on different operating systems: Windows, Linux and macOS.
Exercise Add a comment and output
Add a // comment to the program and print Program is running with Console.WriteLine.
Show example solution
Inside Main, first a // comment, then the Console.WriteLine line.
Example solution:
using System;
class Program
{
static void Main()
{
// Program started
Console.WriteLine("Program is running");
}
}
Test yourself
-
Which command compiles and runs C# code?
- dotnet build
- dotnet new
- dotnet publish
- dotnet run
Show answer
dotnet run — Correct! dotnet run both compiles and runs.
-
Match the dotnet commands
- dotnet run
- Compiles and runs
- dotnet build
- Only compiles
- dotnet new
- Creates a new project
- dotnet publish
- Publishes
-
The run command
The `dotnet ____` command compiles and runs the code.Show answer
The `dotnet run` command compiles and runs the code.