skip to content

In Razor syntax, when does an implicit @expression end early, and when must you write an explicit @( ) expression instead?

level: middleimportance: must knowfreq 55%

answer

  1. where the parser stops reading
  2. spaces end it, await aside
  3. angle brackets look like tags
  4. text glued before the @

basics

~20 s

An implicit @expression reads one identifier chain with member access, calls and indexers, and stops at a space or a character that can't continue it; use @( ) for operators, generic calls, or a value glued to preceding text.

solid answer

~40 s

`@name`, `@line.Sku`, `@lines[0].Sku` and `@Shout("a b")` are implicit expressions: Razor reads an identifier plus member access, calls and indexers, and stops at the first space or character that can't continue it, with `await` the documented exception for spaces. A trailing `.` stays text. So `@lines.Length * 2` writes the length followed by the literal ` * 2`. A generic call breaks because `<int>` is read as an HTML tag: `@Util.Echo<int>(5)` fails the build. And `[email protected]` looks like an email address and prints literally. An explicit expression `@( ... )` evaluates any C# expression between balanced parentheses, as in `@(lines.Length * 2)`, `@(Util.Echo<int>(5))` or `Qty@(line.Qty)`, and its result is HTML-encoded exactly like an implicit one.

code

razor · 10 lines
razor
@{
    var lines = new[] { new Line("A-1", 2, 9.50m), new Line("B-2", 1, 20m) };
    var line = lines[0];
}
<p>@lines.Length * 2</p>
<p>@(lines.Length * 2)</p>
<p>[email protected]</p>
<p>Qty@(line.Qty)</p>
<p>@(Util.Echo<int>(5))</p>
<p>@lines[1].Sku.</p>

go deeper

for a junior

Know that @value prints an encoded value and that @( ) exists for anything the plain form cannot express.

for a middle

Explain exactly where the implicit form stops: at a space other than after await, at a tag-like angle bracket, and why a letter before @ reads as an email address.

for a senior

Diagnose a build error or a half-printed expression in a view by spotting the early stop, and keep complex logic out of expressions.

for a principal

Treat recurring expression bugs as a sign that views carry too much logic; push computation into the model or helpers so markup only prints values.

## Two kinds of Razor expression Razor writes C# values into markup with **expressions**. There are two forms, and both write their result **HTML-encoded** (unless the value is already `IHtmlContent`, such as the result of `Html.Raw`): - an **implicit expression**: `@` followed directly by C#, as in `@customerName`; - an **explicit expression**: `@` followed by balanced parentheses, as in `@(lines.Length * 2)`. The difference is only in **how far the parser reads**. With the implicit form Razor has to guess where the C# ends and the HTML resumes; with the explicit form the closing parenthesis tells it. ## What an implicit expression can contain An implicit expression is an identifier followed by any chain of: - member access: `@line.Sku`; - method calls, whose argument lists may contain spaces: `@Shout("a b c")`; - indexers: `@lines[1].Sku`; - a leading `await`: `@await GetTotalAsync()`, the documented exception to the no-spaces rule. A trailing dot that is not followed by an identifier is left as text, so `@lines[1].Sku.` writes `B-2.` with the full stop as markup. ## Where it stops, and three ways that bites The implicit expression ends at the first character that cannot continue the chain, most often a space. Three classic surprises follow: 1. **Operators and spaces.** `<p>@lines.Length * 2</p>` renders `<p>2 * 2</p>`: the expression is `lines.Length`, and ` * 2` is plain text. 2. **Generic calls.** In `<p>@Util.Echo<int>(5)</p>` the `<int>` looks like an HTML start tag, so the expression stops at the method group `Util.Echo`. On the .NET 10 SDK the build fails with `CS1503: Argument 1: cannot convert from 'method group' to 'object?'`; the docs list similar messages, including an unclosed `int` element. 3. **Text glued in front.** When a letter or digit sits directly before the `@`, Razor reads the run as an email address and leaves it alone, so `<p>[email protected]</p>` renders the literal text `[email protected]`. ## Explicit expressions: `@( ... )` Anything that is a single C# **expression** can go between the parentheses, and Razor evaluates all of it before writing the result: | Want | Implicit attempt | What it does | Explicit fix | |---|---|---|---| | Arithmetic | `@lines.Length * 2` | writes `2 * 2` | `@(lines.Length * 2)` | | Generic call | `@Util.Echo<int>(5)` | build error | `@(Util.Echo<int>(5))` | | Value glued to text | `[email protected]` | literal text | `Qty@(line.Qty)` | | Conditional | `@lines.Length > 1 ? ...` | writes the length, rest as text | `@(lines.Length > 1 ? "items" : "item")` | The explicit form takes an expression, not statements. When the logic needs several statements, compute a local in a `@{ ... }` code block and print it with a plain `@local`. ## Encoding is the same for both The choice between the two forms never changes encoding. `@("<span>Hi</span>")` writes `&lt;span&gt;Hi&lt;/span&gt;` just as `@text` would for the same string. A non-string value is converted with `ToString()` and then encoded; a value that implements `IHtmlContent` is written as it is. ## Reading a symptom back to the cause The early stop shows up in two ways, and each points at a different fix: - **Odd text in the page**, such as `2 * 2` or `[email protected]`, means the expression built but ended earlier than intended; the leftover characters were written as markup. Wrap the whole expression in `@( ... )`. - **A build error on a line that looks right**, such as CS1503 about a method group, means the part Razor did read is not a writable value on its own. The usual culprit is a generic type argument whose angle brackets Razor took for a tag. In both cases the generated C# tells the story. For the generic call the .NET 10 SDK emitted `Write(Util.Echo` followed by `WriteLiteral("<int>(5)</p>")`: a write of only the part Razor recognised, then a literal holding the rest. ## Habits that avoid the surprises - Reach for `@( ... )` as soon as an expression contains an operator, a generic type argument, a ternary or a cast. - When a value must touch the preceding word, use the explicit form instead of inserting a space. - When a build error points at a line that looks fine, check whether an implicit expression ended earlier than you meant. - Keep long logic out of expressions altogether: a well-named local or a helper reads better than a long `@( ... )`.

  • Why can an implicit Razor expression such as @await GetTotalAsync() contain a space when others cannot?
    `await` is the documented exception: Razor knows the keyword is followed by the awaited expression, so it keeps reading past the space and writes the awaited result. The rest of the rules still apply, so `@await GetTotalAsync() * 2` would still stop before the operator; use `@(await GetTotalAsync() * 2)` for that.
  • When should logic move out of an explicit @( ) expression into a @{ } code block?
    When it is more than one expression. `@( ... )` takes a single C# expression, so loops, several statements or anything you want to name belong in a `@{ }` block that assigns a local, which a short `@local` then prints. That keeps the markup readable, and the printed value is encoded either way.

  • An implicit @expression evaluates everything up to the end of the line.
  • Implicit expressions cannot call methods, only read properties.
  • A generic method call works implicitly when the type argument is short.
  • Explicit @( ) output skips HTML encoding.
  • [email protected] prints the quantity glued to the word.