Using C# 9, I encountered the CS1503 error when trying to cast from a generic type implementing a certain interface to that same interface inside a Func
, where the return type is covariant.
Example code:
public interface ITest
{
...
}
public class Test
{
private static readonly Dictionary<Type, Func<string, ITest>> constructors = new();
public static void Register<T>(Func<string, T> constructor) where T : ITest
{
constructors.Add(typeof(T), constructor);
}
}
The error is in the Add
method: Argument 1 cannot convert from Func<string, T> to Func<string, ITest>
.
Oddly, had that interface been a class, the cast works just fine.