A compiler translates source code into another representation. The C# compiler also rewrites source into ordinary .NET-compatible structures, reducing boilerplate and adding features the runtime does not provide directly. section 2.0
Compiler transformations make higher-level C# constructs executable on the .NET runtime:
- Transforms a lambda into a normal method, allowing inline syntax while preserving runtime method-based execution. section 2.1
- Moves captured local variables into a generated class so the generated method and its caller can share state. section 2.1
- Splits yield return code into resumable chunks and wraps them in a class that selects the next chunk. section 2.3
- Transforms async/await into asynchronous continuations and performs additional rewriting so applicable try-catch behavior remains coherent. section 12.1 section 3.1
Timer callback with captured state
A timer can receive an inline lambda that prints "Elapsed" after one second. When the lambda captures a local value, the compiler generates a method plus an object containing that value, then registers the generated method as the callback. section 2.1
Listing 2.1 Using lambda functions
public class LambdaDemo1
{
private System.Timers.Timer? _timer;
public void InitTimer()
{
_timer = new System.Timers.Timer(1000);
_timer.Elapsed += (sender,args) => Console.WriteLine("Elapsed");
_timer.Enabled = true;
}
}
Runnable C# listing showing a lambda assigned to a timer's Elapsed event. section 2.1








