Why does the compiler ask for an explicit cast for a generic – when an implicit one has been defined – only when the generic has been instantiated with an interface?
class G<T>
{
public G(T unused) {}
public static implicit operator G<T>(T unused) => new G<T>(unused);
}
interface I { }
class C : I { }
class Example
{
void Main()
{
G<int> xint1 = 1; // OK
G<int?> xint2 = 1; // OK
G<object> xobject1 = new object(); // OK
G<object?> xobject2 = new object(); // OK
C c = new C();
G<C> gc1 = c; // OK
G<C?> gc2 = c; // OK
I i = c;
G<I> g1 = i;
// ^-- error CS0266: Cannot implicitly convert type 'I' to
// 'G<I>'. An explicit conversion exists (are you missing a
// cast?)
G<I?> g2 = i;
// ^-- error CS0266: Cannot implicitly convert type 'I' to
// 'G<I?>'. An explicit conversion exists (are you missing a
// cast?)
G<I?> g3 = (I?)i;
// ^-- error CS0266: Cannot implicitly convert type 'I' to
// 'G<I?>'. An explicit conversion exists (are you missing a
// cast?)
// ^-- warning CS8600: Converting null literal or possible null
// value to non-nullable type.
G<I?> g4 = (I)i;
// ^-- error CS0266: Cannot implicitly convert type 'I' to
// 'G<I?>'. An explicit conversion exists (are you missing a
// cast?)
}
}