Implicit conversion doesn't work for IReadOnlyCollection

45 Views Asked by At

Here's my code:

public readonly struct Either<TLeft, TRight>
{
    public TLeft? Left { get; } = default;
    public TRight? Right { get; } = default;

    public static implicit operator Either<TLeft, TRight>(TLeft left) => new(left);
    public static implicit operator Either<TLeft, TRight>(TRight right) => new(right);

    private Either(TLeft left) => Left = left;
    private Either(TRight right) => Right = right;
}

public record SomeType(Either<IReadOnlyCollection<int>, int> Something);

public class Class1
{
    public void Run()
    {
        IReadOnlyCollection<int> test1 = new[] { 1, 2 };
        int[] test2 = new[] { 1, 2 };

        var d1 = new SomeType(test1);  // FAILS
        var d2 = new SomeType(test2);  // OK
    }
}

I have the Either type, which contains implicit conversions to simplify its creation. There's also SomeType, which expects Either<IReadOnlyCollection<int>, int> in its constructor. Variables d1 and d2 are two examples of how I'm trying to utilize the implicit conversion. For some reason, d2 works just fine, while d1 has a compilation error:

Argument type 'System.Collections.Generic.IReadOnlyCollection' is not assignable to parameter type 'EitherExperiments.Either<System.Collections.Generic.IReadOnlyCollection,int>'

What's wrong? test1 is of exactly the same type that Either contains in its Left wing.

0

There are 0 best solutions below