Is there a good reason to initialize a property in the SetParameters method rather than directly?

Viewed 164

In the code snippet below, taken from a Blazor sample, the StartDate property is initialized in the derived SetParameters method while it could be initialized thus:

[Parameter] DateTime StartDate { get; set; } = DateTime.Now;  

I wonder if this is a matter of style preference only, or there is a good reason to do so...

  @functions {
    [Parameter] DateTime StartDate { get; set; }

    WeatherForecast[] forecasts;

    public override void SetParameters(ParameterCollection parameters)
    {
        StartDate = DateTime.Now;
        base.SetParameters(parameters);
    }

}

1 Answers

From the blazor documentation:

SetParameters can be overridden to execute code before parameters are set.

If base.SetParameters isn't invoked, the custom code can interpret the incoming parameters value in any way required. For example, the incoming parameters aren't required to be assigned to the properties on the class.

So SetParameters allows you to sneaky modify stuff..

I'm guessing that you are setting the value to have a default. For that I would say that the first method is perfectly fine, and the second method overkill and confusing.

Related