Code blocks
@{ opens a code block that ends at the matching }. What is inside is C# statements; nothing is written unless the code writes it or switches back to markup. Variables declared in a block are visible to later blocks and expressions in the same file.
To find the closing brace the parser reads the C# as tokens, so a } inside any of these does not count: a string ("a}"), a verbatim string (@"a}""}"), an interpolated string ($"{x}}"), a raw string ("""a}"b"""), a character ('}'), a // comment or a /* */ comment. Round and square brackets are balanced as groups, with the same skipping, and a Razor comment @* *@ is allowed anywhere in the block. Braces that open a nested block are counted: @{ if (a) { b(); } } ends at the last brace.
@{
var title = "Orders";
var items = new[] { "a", "b" }; // the braces of the initialiser are balanced
string Label(int n) => $"{n} {{x}}";
}
<h1>@title</h1>
If the closing brace is missing the parser reports that the code block is missing a closing "}" and takes the rest of the file as code. An @{ inside a code block is an error ("Unexpected {" after the @ character): inside a block you are already in C#.
Going back to markup inside code
Inside a block, markup starts at one of four places. The first three apply at the start of a statement: at the start of the block, after a ;, after a }, after the header of a control-flow statement, or after a case ...: or default: label. A < anywhere else is the C# less-than or a generic bracket, which is how if (a < b) and List<int> x; stay code.
| Written | Meaning |
|---|---|
<tag> ... </tag> | Implicit transition. A start tag begins a markup block that runs until the tag is closed. Every start tag in it must be closed or self-closing; the block ends after the end tag of the outermost tag, together with the white space after it up to and including one new line. Void elements (br hr img input meta link area base col embed param source track wbr keygen command) need no end tag when they are the whole block? No: a block must start with a closed tag, so use <br />; a void element nested inside another element is fine. |
<text> ... </text> | Explicit delimited transition. The outermost <text> tag is not written; only its content is. Use it for text that has no tag of its own. It takes no attributes (an error), and it is only special as the outermost tag of a block. |
@: | Explicit line transition. The rest of the line, including the new line, is markup. @ inside it still starts code. Tags in it are plain text to the parser (no balancing). |
@<tag> ... </tag> | An inline template inside an expression: the markup becomes a value, such as a Func<dynamic, object> or a RenderFragment. It may start in the middle of a statement and in a group such as Repeat(items, 3, @<li>@item</li>). Templates cannot nest ("Inline markup blocks cannot be nested"). Written at the start of a statement, @< is reported as an error that asks for a plain tag. |
@foreach (var person in people)
{
var name = person.Name;
<text>Name: @name</text>
@:Age: @person.Age
<p>@person.Email</p>
}
@{
Func<dynamic, object> pet = @<p>A pet named <strong>@item.Name</strong>.</p>;
}
In a view or component all code blocks allow markup, including the bodies of local functions, methods in @functions and @code, and nested blocks inside them (the compiler option that allows this is on for every current language version). A method that contains markup becomes a templating method: calling it writes the markup at the point of the call.
Errors reported for markup in code
- "Markup in a code block must start with a tag and all start tags must be matched with end tags": a block that starts with
<but has no tag name, or an unclosed start tag at the end of the file. - "The element was not closed": an element left open at the end of the block (reported for the outermost one).
- "Encountered end tag with no matching start tag": an end tag that closes nothing. An end tag that matches an element further out closes the inner ones too, and the inner ones are reported as not closed.
- "End of file or an unexpected character was reached before the tag could be parsed": a start tag with no
>. - "Outer tag is missing a name" for
<>at the start of a block.
Control-flow statements
An @ followed by a control-flow keyword starts a statement written without a block of its own: the statement is C#, and its braces are code blocks as above (so they hold markup). It ends where the C# statement ends; no @ is needed on the continuation words.
| Statement | Shape and continuations |
|---|---|
@if | if (cond) { } else if (cond) { } else { }. After the block the parser looks past white space and comments for else; if there is none the white space is markup. |
@for, @foreach, @while, @lock | A parenthesised header, then a block. @await foreach (...) is allowed. |
@switch | A parenthesised header, then a block holding case X: and default: labels. Markup may follow a label directly. |
@do | do { } while (cond);: the block, then while, a header and an optional semicolon. |
@try | try { } catch (E e) when (cond) { } finally { }, with any number of catch clauses, in any order the C# allows. |
@using (...) | A using statement (the keyword is followed by a parenthesis): it holds markup, as in @using (Html.BeginForm()) { ... }. @using Namespace; is a directive instead. Inside a block, using var x = ...; is a C# using declaration. |
If the statement has no block, the single statement that follows is parsed: C# up to its ;. Markup there is reported ("Single-statement control-flow statements in Razor documents cannot contain markup") because the closing of the markup would be ambiguous; put the markup in braces.
A @ inside the block starts a nested expression, and a control-flow keyword inside a block needs no @: @if (a) { foreach (var i in b) { <li>@i</li> } }. An @ in the middle of a C# statement is a verbatim identifier (@class); at the start of a statement it is a nested Razor expression. Anything else after an @ inside a block is the error "The @ character must be followed by a :, (, or a C# identifier".
Errors in code
- A block that never closes: "The code block is missing a closing } character".
- An explicit expression that never closes: "The explicit expression block is missing a closing ) character".
- An opening
(or[in a statement with no closer: "An opening ( is missing the corresponding closing )". - A string that is not terminated before the end of its line (only verbatim and raw strings may span lines): "Unterminated string literal".
- A
/*comment that never ends: "End of file was reached before the end of the block comment".