Search code examples
c#blazorblazor-server-sideblazor-webassembly

Understanding subscribing to an Action<int>


I need help understanding the following.

I declare an Action for when the variable Count changes:

public Action<int>? CountChanged { get; set; }

and then I subscribe to the action as follows:

protected override void OnInitialized()
{
    this.data.CountChanged += (newCount) => this.StateHasChanged();
}

I do not fully understand the line of code below:

this.data.CountChanged += (newCount) => this.StateHasChanged();

My best guess is that it means something like 'when Count changes pass the new value of count as a parameter to the delegate' in this case it is unused, it simply calls the StateHasChanged method. If this is the case, What is the += for?


Solution

  • Firstly, an Action is a delegate.

    There are many ways to add a method to a delegate. As delegates are "multicast" they can hold more than one assigned method. The += adds the method to the right to the delegate while the -= removes it.

    Be careful using =. It will assign the provided method to the delegate and overwrite all previous assignments. delegate = null; clears the delegate.

    The first one below is the most obvious, assigning an existing method. All the others create anonymous methods that are assigned to the action.

        public Action<int>? CountChanged { get; set; }
    
        private int currentCount = 0;
    
        private void IncrementCount()
        {
            currentCount++;
        }
    
        protected override void OnInitialized()
        {
            this.CountChanged += OnCounterChanged;
            this.CountChanged += (int value) => this.StateHasChanged();
            this.CountChanged += (value) => { this.StateHasChanged(); };
            this.CountChanged += value => this.StateHasChanged();
            this.CountChanged += _ => this.StateHasChanged();
        }
    
        private void OnCounterChanged(int value)
        {
            this.StateHasChanged();
        }