In the SharpRune app for iPhone and iPad, tap Run in Preview: the app compiles the Razor components on the device and runs the project on .NET 9. On a computer, download the project and run it with the .NET 9 SDK. The separate C# companion practice below runs in this browser.
From Home.razor to a rendered page
Pages/Home.razor: markup plus@codeHome.razor.csadds members to the samepartialclass- Razor compiler writes
partial class Homederives fromComponentBase; full nameComponentBasics.Pages.Home - Markup becomes
BuildRenderTree@codemembers become ordinary fields and methods of the class - A render records a render tree
@books.Count,@ifand@foreachrun again on every render - Blazor applies only the differencesthe first render builds the page; later renders patch what changed
A component is a C# class, and its markup is a method that describes the UI. Markup expressions run on every render, so keep them cheap and free of side effects.
From a .razor file to a C# class
A Razor component looks like an HTML page with some C# in it, but it is a class. During the build, the Razor compiler reads every .razor file and writes C# source for it. The generated class is public and partial, and it derives from ComponentBase. Its name is the file name, and its namespace is the project's root namespace plus the folder path. That is why Pages/Home.razor in this lesson's project becomes ComponentBasics.Pages.Home, and why the page can print that name with GetType().FullName.
The compiler copies the members of the @code block into the class body as they are. Fields, properties and methods you write there are ordinary C# members. The markup turns into an override of a method named BuildRenderTree. Each element, attribute and piece of text becomes a call on a RenderTreeBuilder, such as opening an element, adding text and closing the element. A @page directive adds a route attribute to the class, which is how the Router finds the page for an address. Because the class is partial, you can add a file named Home.razor.cs that declares partial class Home in the same namespace. Both parts compile into one type, so code in either part can use members from the other.
Razor syntax: expressions, code and control flow
The @ character switches from markup to C#. An implicit expression is @ followed by a name, a member access or a method call, like @books.Count or @GetType().FullName. It ends at the first character that cannot continue the expression, usually a space. An explicit expression is @( ... ) and can hold any C# expression: operators, lambdas, the conditional operator or a generic method call. Generic calls need the explicit form because the < would otherwise start an HTML tag. To write a literal @ in text, use @@.
Control flow uses the C# keywords with an @ in front: @if, @else, @foreach, @for, @while and @switch. Inside their braces you are in C#, but a line that starts with an HTML tag switches back to markup, so you can write elements directly inside a loop. Text from an expression is inserted as text, not as HTML. A title that contains < or & shows those characters on screen instead of creating elements. When you need to insert HTML from a string, MarkupString does that, and you should use it only with content you trust. Razor comments, written as @* comment *@, never reach the browser.
What rendering means in Blazor
When a component renders, Blazor calls its BuildRenderTree method. The method does not touch the browser. It records a render tree: a compact list of elements, attributes, text and child components. The first time, the renderer turns the whole tree into page elements. On later renders, it compares the new tree with the previous one and sends only the differences to the browser. In a Blazor WebAssembly app all of this happens inside the browser tab. The .NET runtime runs your component code, and the script blazor.webassembly.js applies the changes to the page.
This has two consequences for how you write markup. First, every expression in the markup runs again on every render, so VisibleBooks and UnreadCount in this project always reflect current data without extra code. Second, rendering can happen often, so expressions in markup should be cheap and free of side effects. Reading a property is fine. Starting a download, writing to storage or changing a field from inside markup is not, because you do not control how many times it runs.
Trace the reading list
Open Home.razor and Home.razor.cs side by side. The books list, UnreadCount, VisibleBooks and MarkAllUnread live in Home.razor.cs. The unreadOnly field and ToggleFilter live in the @code block. VisibleBooks reads unreadOnly even though it is declared in the other file, which works because both files are parts of the same class. On the first render, @books.Count prints 4, UnreadCount prints 3, and the explicit expression sums the unread pages to 880. The @foreach loop writes four list items. For each one, the inner @if writes either a Read badge or a Mark read button.
Tap Show unread only. The click handler flips unreadOnly, Blazor renders Home again, and VisibleBooks now returns three books. The diff removes one list item and changes the button text; the rest of the page stays as it was. Tap Mark read on each remaining book until VisibleBooks is empty, and the outer @if switches to the Nothing to show paragraph. The console companion follows the same steps with the same data and prints the counts and rows it expects at each stage. It checks the C# decisions, not the rendering.
Common mistakes
An implicit expression that ends too early is the most common surprise. @book.Pages * 2 prints the page count followed by the text " * 2", because the expression stops at the space. Write @(book.Pages * 2) instead. Generic method calls need @( ... ) for the same reason.
Component names must start with an uppercase letter. A file named tip.razor fails to build with error RZ10011, because a lowercase tag always means an HTML element. A tag that starts with an uppercase letter but matches no component builds with warning RZ10012 and renders as an unknown HTML element that shows nothing. That usually means a missing @using for the component's namespace. _Imports.razor is the place for it, because its directives apply to every .razor file in its folder and below.
Finally, keep heavy work out of markup and out of the properties the markup reads. A LINQ query over four books costs nothing, but the same pattern over thousands of records runs on every render, including renders caused by unrelated clicks. Compute expensive results when the data changes and store them in a field.
Practice and review
Add a fifth book in Home.razor.cs and check that every count updates without other changes. Show the average page count with an explicit expression and decide how to format it. Add a third branch inside the list so that books over 400 pages get a Long badge. Move ToggleFilter from the @code block into Home.razor.cs and confirm that nothing else needs to change. Then create a second component that should show the number of unread books, and notice that it cannot see Home's private fields. Lesson 2 shows how a parent passes data to a child through parameters.
- A .razor file compiles into a partial C# class that derives from
ComponentBase; the file and folder decide its name and namespace. - Implicit expressions end at a space; use @( ... ) for operators, lambdas and generic calls.
@ifdecides which markup exists, and@foreachrepeats markup once per item.- A render builds a render tree and Blazor applies only the differences, so markup expressions should be cheap and free of side effects.
A component is a C# class with markup — Blazor WebAssembly project
Run the project
- Tap Run in Preview. SharpRune copies these files into a new project, compiles the Razor components on this device and opens the app in Preview.
- Tap Show unread only, then tap Mark read on each book until the list is empty. Tap Mark all unread and Show all books to get the full list back.
- Change a .razor file and tap Run again to rebuild.
- On a computer: install the .NET 9 SDK, save the files with their folders, and run dotnet run in that folder.
Project files
ComponentBasics.csproj
Download file ↗<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AssemblyName>ComponentBasics</AssemblyName>
<RootNamespace>ComponentBasics</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="9.0.4" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="9.0.4" PrivateAssets="all" />
</ItemGroup>
</Project>
Program.cs
Download file ↗using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using ComponentBasics;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
// <App> replaces <div id="app"> in wwwroot/index.html.
builder.RootComponents.Add<App>("#app");
// HeadOutlet lets <PageTitle> set the browser tab title.
builder.RootComponents.Add<HeadOutlet>("head::after");
await builder.Build().RunAsync();
App.razor
Download file ↗<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<PageTitle>Not found</PageTitle>
<h1>Not found</h1>
<p>There is no page at this address.</p>
</NotFound>
</Router>
_Imports.razor
Download file ↗@using System.Net.Http
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using ComponentBasics
@using ComponentBasics.Components
Pages/Home.razor
Download file ↗@page "/"
<PageTitle>Reading list</PageTitle>
<h1>Reading list</h1>
@* An implicit expression: @ followed by a name, member access or method call. *@
<p>You have @books.Count books. @UnreadCount of them are unread.</p>
@* An explicit expression: @( ... ) holds any C# expression, with spaces, operators and lambdas. *@
<p>Pages still to read: <strong>@(books.Where(book => !book.Read).Sum(book => book.Pages))</strong></p>
<div class="row">
@* @onclick is covered in lesson 3. Here it only changes data, so you can watch the markup follow. *@
<button class="primary" @onclick="ToggleFilter">@(unreadOnly ? "Show all books" : "Show unread only")</button>
<button @onclick="MarkAllUnread">Mark all unread</button>
</div>
@if (VisibleBooks.Count == 0)
{
@* @if decides which markup exists at all. This branch shows up when the filter hides every book. *@
<p class="empty">Nothing to show: every book is read.</p>
}
else
{
<ul class="books">
@foreach (var book in VisibleBooks)
{
@* @foreach repeats this <li> once per book. *@
<li class="@(book.Read ? "read" : "")">
<span class="title">@book.Title</span>
<span class="muted">@book.Pages pages</span>
@if (book.Read)
{
<span class="badge">Read</span>
}
else
{
<button class="link" @onclick="() => book.Read = true">Mark read</button>
}
</li>
}
</ul>
}
<p class="muted">This page is the C# class <code>@GetType().FullName</code>. Its base class is <code>@(GetType().BaseType?.Name)</code>.</p>
<RazorNote />
@code {
// Members in @code are copied into the generated Home class.
// Home.razor.cs adds more members to the same class.
private bool unreadOnly;
private void ToggleFilter() => unreadOnly = !unreadOnly;
}
Pages/Home.razor.cs
Download file ↗namespace ComponentBasics.Pages;
// The Razor compiler turns Home.razor into "public partial class Home : ComponentBase"
// in the namespace ComponentBasics.Pages (root namespace + folder). This file is a second
// part of that same class, so it can use unreadOnly from the @code block and vice versa.
public partial class Home
{
private readonly List<Book> books =
[
new("Rivers of Code", 320),
new("The Quiet Compiler", 210) { Read = true },
new("Patterns at Dawn", 410),
new("A Short Guide to Types", 150),
];
// Properties are read on every render, so the markup always shows current data.
private int UnreadCount => books.Count(book => !book.Read);
private List<Book> VisibleBooks => unreadOnly ? books.Where(book => !book.Read).ToList() : books;
private void MarkAllUnread()
{
foreach (var book in books)
{
book.Read = false;
}
}
}
public sealed class Book(string title, int pages)
{
public string Title { get; } = title;
public int Pages { get; } = pages;
public bool Read { get; set; }
}
Components/RazorNote.razor
Download file ↗@* Components/RazorNote.razor becomes a class named RazorNote in ComponentBasics.Components.
_Imports.razor imports that namespace, so Home.razor can write the tag <RazorNote />. *@
<aside class="note">
<strong>How this page is built</strong>
<p>Home.razor (markup and <code>@@code</code>) and Home.razor.cs are two parts of one class, Home.</p>
<p>This box is a separate class, <code>@GetType().FullName</code>. Home places it with the tag <code><RazorNote /></code>, the way you would use an HTML element.</p>
</aside>
wwwroot/index.html
Download file ↗<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Reading list</title>
<base href="/" />
<link rel="stylesheet" href="css/app.css" />
<link rel="stylesheet" href="ComponentBasics.styles.css" />
</head>
<body>
<div id="app">
<p class="loading">Starting .NET…</p>
</div>
<div id="blazor-error-ui">
An unhandled error has occurred.
<a href="." class="reload">Reload</a>
<span class="dismiss">✕</span>
</div>
<script src="_framework/blazor.webassembly.js"></script>
</body>
</html>
wwwroot/css/app.css
Download file ↗:root {
color-scheme: light dark;
--accent: #6b4eff;
--line: #d8d6e4;
--muted: #777;
}
body {
margin: 0;
font-family: -apple-system, system-ui, sans-serif;
line-height: 1.5;
}
#app {
max-width: 720px;
margin: 0 auto;
padding: 20px 16px 40px;
box-sizing: border-box;
}
a, button, input, label {
touch-action: manipulation;
}
h1 {
font-size: 1.8rem;
margin: 0 0 12px;
}
h1:focus {
outline: none;
}
h2 {
font-size: 1.15rem;
margin: 0 0 8px;
}
.loading {
padding: 32px 16px;
color: var(--muted);
}
.row {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin: 12px 0;
}
input:not([type=checkbox]), select {
font: inherit;
padding: 8px 10px;
border: 1px solid var(--line);
border-radius: 8px;
min-width: 0;
background: transparent;
color: inherit;
}
button {
font: inherit;
padding: 8px 14px;
border-radius: 8px;
border: 1px solid var(--line);
background: transparent;
color: inherit;
}
button.primary {
background: var(--accent);
border-color: var(--accent);
color: #fff;
}
button:disabled {
opacity: 0.45;
}
button.link {
border: none;
color: var(--accent);
padding: 4px 6px;
}
.muted {
color: var(--muted);
}
.card {
border: 1px solid var(--line);
border-radius: 12px;
padding: 14px 16px;
margin: 16px 0;
}
.card > :last-child {
margin-bottom: 0;
}
code {
font-family: ui-monospace, Menlo, monospace;
font-size: 0.9em;
overflow-wrap: anywhere;
}
.books {
list-style: none;
padding: 0;
margin: 16px 0;
}
.books li {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px 10px;
padding: 10px 0;
border-bottom: 1px solid var(--line);
}
.books .title {
font-weight: 600;
flex: 1 1 100%;
}
.books li.read .title {
color: var(--muted);
}
.badge {
font-size: 0.8rem;
padding: 2px 8px;
border-radius: 999px;
background: #2f9e6e;
color: #fff;
}
.empty {
padding: 16px;
border: 1px dashed var(--line);
border-radius: 12px;
color: var(--muted);
}
.note {
margin-top: 20px;
padding: 12px 16px;
border-left: 4px solid var(--accent);
background: rgba(107, 78, 255, 0.08);
border-radius: 8px;
}
.note p {
margin: 6px 0 0;
}
#blazor-error-ui {
display: none;
position: fixed;
bottom: 0;
left: 0;
right: 0;
padding: 12px 16px;
background: #ffe8a3;
color: #222;
}
Expected result
The page starts with 4 books, 3 unread and 880 pages still to read. Show unread only hides The Quiet Compiler and the button text changes to Show all books. With the filter off, Mark read swaps the button for a green Read badge; with the filter on, the book leaves the list. Either way the unread and page counts drop. With the filter on and every book read, the list is replaced by "Nothing to show: every book is read." Below the list the page names its class, ComponentBasics.Pages.Home, with base class ComponentBase, and the note box names ComponentBasics.Components.RazorNote.
The project runs in the SharpRune app and with the .NET 9 SDK. Open C# practice runs the separate portable exercise.
C# companion practice
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
// The same data and decisions as Home.razor, without Blazor.
var books = new List<Book>
{
new("Rivers of Code", 320),
new("The Quiet Compiler", 210) { Read = true },
new("Patterns at Dawn", 410),
new("A Short Guide to Types", 150),
};
Render("All books", books, unreadOnly: false);
Render("Unread only", books, unreadOnly: true);
foreach (var book in books) book.Read = true; // like tapping every "Mark read" button
Render("Unread only, all read", books, unreadOnly: true);
// One "render": the page's expressions, @if and @foreach, writing lines instead of elements.
static void Render(string label, List<Book> books, bool unreadOnly)
{
var visible = unreadOnly ? books.Where(book => !book.Read).ToList() : books;
int unread = books.Count(book => !book.Read);
int pagesLeft = books.Where(book => !book.Read).Sum(book => book.Pages);
Console.WriteLine($"{label}: {books.Count} books, {unread} unread, {pagesLeft} pages to read");
if (visible.Count == 0)
{
Console.WriteLine(" Nothing to show: every book is read.");
return;
}
foreach (var book in visible)
{
string action = book.Read ? "Read" : "Mark read";
Console.WriteLine($" {book.Title} | {book.Pages} pages | {action}");
}
}
sealed class Book(string title, int pages)
{
public string Title { get; } = title;
public int Pages { get; } = pages;
public bool Read { get; set; }
}
C# practice output
All books: 4 books, 3 unread, 880 pages to read Rivers of Code | 320 pages | Mark read The Quiet Compiler | 210 pages | Read Patterns at Dawn | 410 pages | Mark read A Short Guide to Types | 150 pages | Mark read Unread only: 4 books, 3 unread, 880 pages to read Rivers of Code | 320 pages | Mark read Patterns at Dawn | 410 pages | Mark read A Short Guide to Types | 150 pages | Mark read Unread only, all read: 4 books, 0 unread, 0 pages to read Nothing to show: every book is read.
An implicit expression stops at the first space, so @book.Pages * 2 prints the number followed by " * 2". Wrap anything with operators in @( ... ).