'Blazor: There is no boxing conversion or type parameter conversion from 'T' to 'System.IComparable<T>

Blazor doesn't seem to grasp my generic type constraints when using @typeparam. The following setup gives a compilation error:

error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'MyObject<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IComparable<T>'.

MyObject.cs

public class MyObject<T>
    where T : IComparable<T>
{
    public MyObject(T value)
    {
        Value = value;
    }

    public T Value { get; }
}

MyComponent.razor

@typeparam T where T : IComparable<T>
<div>
    @MyObject.Value
</div>

@code {
    [Parameter]
    public MyObject<T> MyObject { get; set; }
}

MainComponent.razor

<MyComponent MyObject="@value" />

@code {
    private MyObject<decimal> value = new MyObject(21M);
}

I know I can add the type parameter explicitly, by doing this:

<MyComponent T="decimal" MyObject="@value" />

But in the codebase I'm about to write that will get very very cumbersome. It feels like blazor is supposed to be able to implicitly determine the type parameter used in the above example.

Is there a way to make this implicit type determination possible?

I'm using net6.0



Solution 1:[1]

If MyObject<decimal> value was a parameter in the constructor for MyComponent then it would make sense that T could be implicitly determined. But Blazor needs to construct a new MyComponent long before any parameters in the type are actually set. So Blazor would have to know that you set all the parameters necessary for determining all type parameters, which it apparently doesn't do.

And you can see this by putting a breakpoint in the OnInitialized function of your component and seeing that value will not yet have any value.

You can see the lifecycle of the component here.

Plain C# example:

MyComponent c = new MyComponent<decimal>();  // <--- How must Blazor know this is a decimal here?
c.value = new MyObject(21M);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 maraaaaaaaa