skip to content

In a Blazor component, how do [Parameter] and [EditorRequired] declare inputs, and why shouldn't the component assign its own parameter property?

level: juniorimportance: must knowfreq 70%

answer

  1. public auto property with a public setter
  2. BL0001 and BL0004 are errors
  3. EditorRequired warns at build time only
  4. no required or init on parameters
  5. the parent's next render overwrites it

basics

~20 s

A parameter is a public auto property marked [Parameter]; adding [EditorRequired] makes the editor and build warn when a caller omits it, but nothing enforces it at runtime. A component should not assign its own parameter, because a later parent render can pass its value again and overwrite the change.

solid answer

~50 s

A Razor component, a `.razor` file compiled into a partial class (optionally with a `.razor.cs` code-behind), declares inputs as **public auto properties** marked `[Parameter]`; the Blazor analyzers report a non-public parameter (BL0004) or a non-public setter (BL0001) as errors and a parameter with logic in its accessors (BL0007) as a warning. `[Parameter, EditorRequired]` makes the Razor tooling warn at design and build time when a caller leaves the parameter out, but it is not checked at runtime and does not guarantee a non-null value; the C# `required` and `init` modifiers are bypassed because Blazor sets parameters by reflection. If the component writes to its own parameter, the value only lasts until the parent next re-applies parameters - when the parent's value changes, or on every parent render if the child also takes an object-typed parameter such as `ChildContent`. Copy the parameter into a private field (in `OnInitialized` for an initial value) and raise an `EventCallback` when the parent should change it.

code

csharp · 14 lines
csharp
public partial class VehicleCard
{
    [Parameter, EditorRequired]
    public Vehicle Vehicle { get; set; } = default!;

    [Parameter]
    public bool InitiallyExpanded { get; set; }

    private bool expanded;

    protected override void OnInitialized() => expanded = InitiallyExpanded;

    private void Toggle() => expanded = !expanded;
}

go deeper

for a junior

Recall the public auto property with [Parameter], how a parent sets it as an attribute, and that [EditorRequired] gives a warning, not a runtime check.

for a middle

Explain why required and init do not help, which analyzer rules apply, and when a parent re-render re-applies parameters and overwrites a value the child assigned itself.

for a senior

Diagnose state that snaps back after unrelated renders, and restructure the component into a private field plus an EventCallback so ownership stays with the parent.

for a principal

Set component API conventions for a team - required markers, no self-assigned parameters, EventCallback for changes - so shared components behave predictably when parents re-render.

## What a component parameter is A **Razor component** is a `.razor` file that the Razor compiler turns into a C# **partial class** named after the file (`VehicleCard.razor` becomes class `VehicleCard`, in a namespace derived from the project and folder). Code can live in an `@code` block or in a **code-behind** file `VehicleCard.razor.cs` declaring `public partial class VehicleCard`. A **component parameter** is how a parent passes data in: a property marked with `[Parameter]` (`Microsoft.AspNetCore.Components.ParameterAttribute`) that the parent sets with an attribute of the same name, as in `<VehicleCard Vehicle="@truck" ShowMileage="true" />`. ## The shape Blazor expects The `Microsoft.AspNetCore.Components.Analyzers` package that ships with Blazor checks parameter declarations: | Diagnostic | Severity | Rule | |---|---|---| | `BL0004` | error | a component parameter should be public | | `BL0001` | error | a component parameter should have a public setter | | `BL0007` | warning | component parameters should be auto properties | | `BL0005` | warning | a component parameter should not be set outside its component | | `BL0002` / `BL0003` | warning | at most one `CaptureUnmatchedValues` parameter, and it must have a suitable dictionary type | So the canonical form is `[Parameter] public Vehicle? Vehicle { get; set; }`, with no logic in the accessors. A default value goes in an initializer (`= true`) and applies when the parent does not supply the attribute. ## Required parameters: [EditorRequired] `[EditorRequired]` (`EditorRequiredAttribute`), placed next to `[Parameter]`, tells the Razor tooling that callers must supply the parameter: - the editor and the build show a warning at a call site that omits it; - it is **not enforced at runtime** and does not guarantee the value is non-null - a parent can still pass `null` explicitly; - it is only valid on a property that is also a `[Parameter]`. The C# `required` modifier and `init` accessor look tempting but are the wrong tool: Blazor creates components and assigns parameters through `ParameterView.SetParameterProperties`, which uses reflection, so the compiler's guarantees for `required` and `init` never apply. A component that truly cannot work without a value should still check it, for example in `OnParametersSet`, and throw a clear exception. ## Why a component must not overwrite its own parameter Parameters flow **down**. Each time the parent renders, Blazor compares the new attribute values with the old ones and calls the child's `SetParametersAsync` when something may have changed. Two details make self-assignment fragile: 1. Blazor compares the values the parent passed in its previous render with the ones it passes now. When every parameter is a simple type - strings, numbers, `DateTime`, `Guid`, `DateOnly`, `TimeOnly`, `EventCallback` - and none changed, the child is skipped. For any other object type, including a `RenderFragment` such as `ChildContent`, Blazor cannot prove nothing changed, so every parent render pushes all the parameters again. 2. Pushing the parameters again **overwrites** whatever the child assigned to a parameter the parent supplies. The classic bug is a collapsible panel with `ChildContent` that sets its own `[Parameter] public bool Expanded` when clicked: it toggles, then snaps back the next time the parent renders for an unrelated reason. The docs' guidance is plain: providing initial values is fine, but do not write to your own parameters after the first render. The fix keeps two separate things: - a **private field** holding the component's own state, seeded from the parameter (for example `expanded = InitiallyExpanded;` in `OnInitialized`); - an **`EventCallback`** the component raises when the parent should change the value, so the parent stays the owner and passes it back down. `BL0005` covers the opposite direction: a parent that grabs a child with `@ref` and assigns `child.Vehicle = x` bypasses rendering and is flagged too. ## Fleet example In a fleet-maintenance app, a `VehicleCard` receives `Vehicle` from the page's list. It shows a local edit form; edits go into a private copy and are raised with `OnSaved`, never written back into `Vehicle`, so a refresh of the page's list cannot silently discard or corrupt them.

  • Why does a child that receives a List<WorkOrder> parameter re-render every time its parent does?
    Blazor skips re-setting a child's parameters only when every value is of a type it treats as immutable - primitives, `string`, `decimal`, `DateTime`, `Guid`, `DateOnly`, `TimeOnly` and `EventCallback` - and is equal to the old one. A `List<WorkOrder>` is a mutable object type, so Blazor assumes it may have changed and calls `SetParametersAsync` on the child whenever the parent renders.
  • What does [Parameter(CaptureUnmatchedValues = true)] do?
    It turns one parameter, typically `IReadOnlyDictionary<string, object>`, into a bucket for every attribute the caller passed that matches no other parameter. The component can splat them onto an element with `@attributes`, which is how wrapper components forward `class`, `aria-*` or `data-*` attributes. Only one such parameter is allowed per component; the analyzers warn otherwise.

  • Marking a parameter with [EditorRequired] makes Blazor throw at runtime when it is missing.
  • Using the C# required modifier on a parameter guarantees callers always set it.
  • Parameters can be private fields marked [Parameter] as long as the component reads them.
  • A child can update its own parameter property and the new value is guaranteed to survive parent renders.
  • Setting child.Vehicle through an @ref is the normal way for a parent to update a child.