Introduction to C# Bytecode: Behind the Scenes


C# code is compiled into Common Intermediate Language (CIL) bytecode, which is executed by the .NET Common Language Runtime (CLR) or .NET Core Runtime. While you can't directly write or interact with CIL in C#, you can explore it by examining the assembly code generated by the C# compiler.


Sample C# Code and Bytecode


Here's a basic example of C# code and the corresponding bytecode:


using System;
class Program
{
static void Main()
{
int a = 10;
int b = 20;
int sum = Add(a, b);
Console.WriteLine("Sum: " + sum);
}
static int Add(int x, int y)
{
return x + y;
}
}

Compile the above C# code and use the IL Disassembler tool (Ildasm) to view the bytecode. You can execute Ildasm from the Visual Studio Developer Command Prompt or any other development environment with the .NET SDK installed. Here's the command:


ildasm /out=Program.il Program.exe

Now, open Program.il in a text editor to explore the CIL bytecode. You'll see the bytecode instructions that correspond to the C# code.


Keep in mind that this is an advanced topic, and examining CIL bytecode is typically done for educational or debugging purposes. In regular C# development, you work with the high-level C# language and do not need to interact with the CIL bytecode directly.