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?
initalso was my first idea and, after read OP comment, I guess "code-behind" is the only way to match readonly properties requirement. I elaborate an answer with this.