0
0
C Sharp (C#)programming~5 mins

How C# compiles and runs on CLR

Choose your learning style9 modes available
Introduction

C# code needs to be changed into a form the computer understands before it can run. The CLR helps by running this changed code safely and efficiently.

When you write a C# program and want it to run on any Windows computer.
When you want your program to be safe and manage memory automatically.
When you want to use features like garbage collection and security checks.
When you want your program to work with other .NET languages easily.
When you want your program to run faster by using just-in-time compilation.
Syntax
C Sharp (C#)
C# source code --(compiled by C# compiler)--> Intermediate Language (IL) code --(run by CLR using Just-In-Time compiler)--> Machine code executed by CPU
The C# compiler changes your code into Intermediate Language (IL), not directly into machine code.
The CLR runs the IL code and converts it to machine code just before running it, making programs flexible and safe.
Examples
This C# code is compiled into IL code first.
C Sharp (C#)
// C# source code example
class Program {
    static void Main() {
        System.Console.WriteLine("Hello, CLR!");
    }
}
The IL code is what the CLR understands and runs.
C Sharp (C#)
// IL code example (simplified)
.method public hidebysig static void Main() cil managed {
    // IL instructions here
}
Sample Program

This simple program prints a message. When you compile it, the C# compiler creates IL code. The CLR then runs this IL code by converting it to machine code on your computer.

C Sharp (C#)
using System;

class Program {
    static void Main() {
        Console.WriteLine("Hello from C# running on CLR!");
    }
}
OutputSuccess
Important Notes

The CLR manages memory automatically using garbage collection, so you don't have to free memory manually.

Just-In-Time (JIT) compilation happens when the program runs, turning IL into machine code for your specific CPU.

The CLR also provides security and error handling to keep your program safe.

Summary

C# code is first compiled into Intermediate Language (IL) code.

The CLR runs the IL code by converting it to machine code just before execution.

This process makes C# programs safe, flexible, and able to run on different computers.