.NET › Blazor (Server & WebAssembly)

How do Razor components (.razor files) combine markup and C# code, and what is the @code block?

Intermediate

Answer

A .razor component file mixes HTML-like markup with embedded C# expressions (using @ syntax) for data binding and control flow, plus an @code block containing the component's C# class members (properties, fields, methods, lifecycle overrides) -- Blazor compiles this into a regular C# class at build time, with the markup becoming a BuildRenderTree method.
<h3>@Title</h3>
<button @onclick="IncrementCount">Count: @count</button>

@code {
    [Parameter] public string Title { get; set; } = "Counter";
    private int count = 0;
    private void IncrementCount() => count++;
}
Real-world example A reusable Counter.razor component exposes a Title parameter so it can be embedded multiple times on a page with different labels, each maintaining its own independent count state.

Common follow-ups: How do [Parameter] properties enable passing data from parent to child components?;What does the generated BuildRenderTree method actually do?