Home > front end >  blazor - EditorRequired attribute
blazor - EditorRequired attribute

Time:07-18

 @code {
     [Parameter, EditorRequired] 
     public Trail Trail { get; set; } = default!;
 }

What does this mean

  1. EditorRequired
  2. public Trail Trail { get; set; } = default!; (why default and why exclamatory mark?)

CodePudding user response:

What does this mean

  1. EditorRequired

It is a hint to the user of your component that Trail is a required parameter. When you 'forget' Trail, as in <MyComponent /> you will get a warning, and some squiggly lines under that usage.
The warning in your Build output is

RZ2012 Component 'MyComponent' expects a value for the parameter 'Trail', but a value may not have been provided.

  1. public Trail Trail { get; set; } = default!;
    (why default and why exclamatory mark?)

This is a way to reduce warnings. When you omit = default!; you will get the warning:

CS8618 Non-nullable property 'Trail' must contain a non-null value when exiting constructor.

Together these two features provide a reasonable way to work with nullable reference types in Blazor. It is not air-tight, you can still get null-reference exceptions. But not as easily anymore.

What you have here is a standard pattern and a best-practice.

  • Related