When to use Property and when to use private variable in Blazor classes?

79 views Asked by At

I am confused when to use Public Property and When to use private variable in Blazor code behind classes. Is there any performance implications using one over other.

3

There are 3 answers

6
Grizzlly On

No, no performance implications.

Use properties when a field expresses a property of the component. Take a look at component parameters. Additionally, fields annotated with [Inject] should be properties.

Use fields when you are expressing some internal state for the component such as whether or not a modal is shown, an element reference, and EditContext or a model from a form, etc.

The thing with properties is that you can insert some additional login in the getters and setters. This can have performance implications though, because if you call StateHasChanged() in one of them and the component is updated frequently your page will become unresponsive. Most of the situations where you would want this logic come down to data binding. Take a look at the docs: ASP.NET Core Blazor data binding.

1
Henk Holterman On

Base rule: Use public properties when you must, private fields otherwise.

You need properties for [Inject] and [Parameter] .

There are no direct performance considerations here.

A Blazor component is usually not used from outside itself. When you do do that the normal rules for encapsulation apply. I.e, only make something public when required.

0
MrC aka Shaun Curtis On

In general you should not be consuming components, passing them around and calling methods or setting properties on them externally. They are created, owned and managed by the Renderer.

There are therefore very few reasons to have public properties and methods.

Everything in my components is by default private. [Parameters] have to be public because they won't compile otherwise. Technically I don't think they need to be, but that's a compiler requirement. Interestingly a cascading parameter can be private.

I use protected methods and properties in base components where required.