Search code examples
c#asp.net-coreblazorblazor-server-side.net-8.0

How to bind to an inherited class in a component?


I have the following classes:

public interface IClass1
{
    string Name { get; set; }
}

public class Class1 : IClass1
{
    public string Name { get; set; }
}

public class Class2 : Class1
{ 
    public string Description { get; set; }
}

I have a razor component ClassComponent with the following parameters:

@code {
    [Parameter]
    public Class1 Model { get; set; }

    [Parameter]
    public EventCallback<Class1> ModelChanged { get; set; }
}

I then have 2 pages. Page 1:

<ClassComponent @bind-Model="model" />

@code {
    private Class1 model = new();
}

and Page 2:

<ClassComponent @bind-Model="model" />

@code {
    private Class2 model = new();
}

Everything works fine in Page 1. However, I cannot use the same logic in Page 2 as I get the following compiler error:

CS1662: Cannot convert anonymous method block to delegate type 'delegate type' because some of the return types in the block are not implicitly convertible to the delegate return type

Is it possible to implement the above in another way that will work?


Solution

  • Use generics with a constraint:

    @typeparam T where T : Class1
    <h3>ClassComponent</h3>
    
    @code {
        [Parameter]
        public T Model { get; set; }
    
        [Parameter]
        public EventCallback<T> ModelChanged { get; set; }
    }
    

    https://learn.microsoft.com/en-us/aspnet/core/blazor/components/generic-type-support?view=aspnetcore-9.0