vernou
vernou

Reputation: 7590

Initialize objects in Blazor component

With this Blazor component:

@page "/counter"

<h1>Counter</h1>

<p>Current count: @_a.CurrentCount</p>

<button class="btn btn-primary" onclick="@_b.IncrementCount">Click me</button>

@functions {
    private readonly ClassA _a = new ClassA();
    private readonly ClassB _b = new ClassB(_a);

    class ClassA
    {
        public int CurrentCount { get; set; }
    }

    class ClassB
    {
        private readonly ClassA _classA;

        public ClassB(ClassA classA)
        {
            _classA = classA;
        }

        public void IncrementCount() => _classA.CurrentCount++;
    }
}

I get this error:

Error CS0236 A field initializer cannot reference the non-static field, method, or property '__Counter._a'

This thread explain how resolve this error in standard class:

Why can't you use 'this' in member initializers?

But for this, it needs a constructor.

Is it possible to add constructor in Blazor component?

How resolve this error?

Upvotes: 7

Views: 15127

Answers (1)

dani herrera
dani herrera

Reputation: 51645

To keep classes readonly you should to move to "code-behind". Then you can instantiate classes on constructor:

@page "/counter"
@inherits CounterBase
<h1>Counter</h1>

<p>Current count: @_a.CurrentCount ...

CounterBase.cs

using Microsoft.AspNetCore.Blazor.Components;

namespace YourApp.Pages
{

    public class ClassA
    {
        public int CurrentCount { get; set; }
    }

    public class ClassB
    {
        private readonly ClassA _classA;

        public ClassB(ClassA classA)
        {
            _classA = classA;
        }

        public void IncrementCount() => _classA.CurrentCount++;
    }

    public class CounterBase : BlazorComponent
    {
        protected readonly ClassA _a;
        protected readonly ClassB _b;

        //constructor
        public CounterBase()
        {
            _a = new ClassA();
            _b = new ClassB(_a);
        }
        ...

Upvotes: 8

Related Questions