Search code examples
c#asp.net-coreblazorasp.net-core-8

Blazor 8 Delegate Type Could Not Be Inferred


I am migrating my Blazor Server from .NET 7 to 8. Apparently it causes error on calling the function this way:

<input type="checkbox" class="form-check" checked="@isChecked" 
       @onchange="@((e) => AddRemoveSelection((int)i.Id!, Convert.ToBoolean(e.Value)))" />

The compiler says

The delegate type could not be inferred

and highlighted => arrow function with red underline.

Here is the method:

private void AddRemoveSelection(int id, bool isSelected)
{
    if (isSelected)
    {
        // Adding ids to selection
        if (!selectedIds.Any(s => s == id))
        {
            selectedIds.Add(id);
        }
    }
    else
    {
        var s = selectedIds.Find(s => s == id);
        selectedIds.Remove(s);
    }
}

Is there any change in Blazor on .NET 8 that disables this syntax?


Solution

  • I can't generate the error with the code you've show.

    The normal issue when you see this is the IDE/Razor Compiler have got themselves in a twist. I find that restarting the solution normally fixes it. Moving the files outside the IDE [using say File Manager] also often works.

    Here's my MRE based on your code. I've added a refactored version of the input and method that moves all the type conversion to the method.

    @page "/"
    
    <PageTitle>Home</PageTitle>
    
    <h1>Hello, world!</h1>
    
    Welcome to your new app.
    
    <input type="checkbox" class="form-check" checked="@isChecked"
           @onchange="@((e) => AddRemoveSelection((int)i.Id!, Convert.ToBoolean(e.Value)))" />
    
    <input type="checkbox" class="form-check" checked="@isChecked"
           @onchange="e => AddRemoveSelection1(i.Id, e)" />
    
    @code{
        private bool isChecked;
        private Data i = new();
    
        private void AddRemoveSelection(int id, bool isSelected)
        {
            // Do something
        }
    
        // Alternative method
        // let the method do the type conversion work
        private void AddRemoveSelection1(object? id, ChangeEventArgs e)
        {
            //do int convertion
            if (!bool.TryParse(e.Value?.ToString(), out isChecked))
                isChecked = false;
            // Do something
        }
    
        public class Data
        {
            public int Id { get; set; }
        }
    }