When I try to build a Blazor component I can define parameters for it like this:
@code {
[Parameter]
public string MyString { get; set; }
}
My question is can I make this parameter required so that, when component is used, the project will not build unless I provide the specified parameter? Is this something I should even be worried about? I suppose I could handle any invalid values in component initialization by maybe throwing an exception if the value is not provided like this:
protected override void OnInitialized()
{
base.OnInitialized();
if (string.IsNullOrWhiteSpace(MyString)) {
// throw an exception here...
}
}
but is that the right way to handle this?
.NET 6 and newer
This can be accomplished with the [EditorRequired]
attribute. Example:
[Parameter, EditorRequired]
public string Name { get; set; }
This will give an IDE warning to consumers of components that parameters are missing if their parameters are not supplied.
Before .NET 6
Currently, you’ll have to do exactly as you said.
As @BenSampica said, gotta wait until .NET 6 for this, but you can use
[Parameter]
public string MyString { get; set; } = null!;
for now. Won't generate compiler error, but won't let you use it either.
Not yet, no. The best you can do at the moment is to throw an exception in SetParametersAsync
.
There's a section on optional route parameters on Blazor University that will show how to check if a parameter was passed or not. You simply make it nullable and check it isn't null. https://blazor-university.com/routing/optional-route-parameters/
Alternatively, if override SetParametersAsync
you are passed a ParameterView parameters
parameter, you can use parameters.TryGetValue
to determine if a parameter was passed, and throw an exception if it wasn't.
But there is currently no way to cause compile-time errors.
I like to combine [EditorRequired]
with an initial value of null!
.
[Parameter, EditorRequired]
public string MyString { get; set; } = null!;
Technically, the value will be null before OnInitialized()
runs, such as in the constructor. Still, it's more convenient than having to treat it as possibly null everywhere else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With