Compiling and Running C# Code

Lesson 1.4: Compiling and Running C# Code


You've written your first C# program, but how do you get it to run? This lesson explains the two key steps: compilation and execution.


Step 1: Compilation


What is Compilation?


Think of your C# code as a set of instructions written in a language that humans understand. Computers, however, need a different language – one made up of binary code (0s and 1s).

Compilation is the process of translating your human-readable C# code into a language that the computer can understand and execute.

This translation is done by a special program called a compiler.

The C# Compiler:


The C# compiler is part of the .NET SDK (Software Development Kit).

It takes your C# source code files (with the .cs extension) and produces an output file called an assembly.

The assembly contains Intermediate Language (IL) code, which is a lower-level representation of your program.

How Visual Studio Helps:


In Visual Studio, compilation usually happens automatically behind the scenes. When you press the "Start" button or F5, Visual Studio compiles your code and then runs it.

This automatic compilation makes life easier for beginners.

Compiling Manually (Optional):


If you're using Visual Studio Code or want to understand the process better, you can compile your code manually using the .NET CLI (Command Line Interface):

Open a terminal or command prompt.

Navigate to the directory containing your C# project.

Type the following command and press Enter: dotnet build

This will compile your code, and if successful, you'll see a message indicating that the build succeeded.

Step 2: Running (Executing) the Code


What is Execution?


Execution is the process of running the compiled code on your computer.

The .NET runtime environment takes the IL code from the assembly and translates it into machine code (the actual 0s and 1s) that your computer's processor can execute.

Running in Visual Studio:


In Visual Studio, running your code is simple: just press "Start" or F5.

Visual Studio will compile your code (if it hasn't already) and then start the .NET runtime to execute the assembly.

Running Manually (Optional):


You can also run your compiled code from the command line:

Open a terminal or command prompt.

Navigate to the output directory where your assembly file is located.

Type the following command and press Enter: dotnet run

This will start the .NET runtime and execute your program.

Key Points to Remember


Compilation is Translation: It turns your C# code into a language the computer understands.

Execution is Action: It's when your program actually runs.

Visual Studio Simplifies Things: It handles compilation and running automatically.

The .NET CLI is Powerful: It gives you more control over the process.

Let me know if you have any other questions!

Course Syllabus