When I try to use a user-defined cast operator from an interface type to a generic struct type, I get a compile error stating the type can’t be converted:
public interface J { }
public struct S<T> {
public static explicit operator S<T>(T value) {
return new S<T>();
}
}
public static class C {
public static S<J> Test(J j) {
return (S<J>)j; // <- error: cannot convert type 'J' to type 'S<J>'
}
}
Note that if J were a class, the conversion would work.
There is a similar question about converting to a class, with the answer being that a derived class might implement the interface and create ambiguity over whether the user-defined cast should be used. But for structs there can be no derived type, and the compiler knows that my struct does not implement J.
Perhaps it’s to avoid unexpected semantic changes as interfaces implementations new interfaces? Maybe it’s just accidental? Maybe I’m making a naive mistake? A quote from the spec would be great, but really I’d like the reason it was designed that way in the first place.
Well, the system can’t do an actual cast because
S<J>does not implementJ. It works fine if you change your declaration:In the case of classes, it’s possible for a sub-type of a class to be declared which does implement
J. But structs cannot be extended, so ifSdoesn’t implementJthen you can guarantee that no class that “is a”Swill ever implementJeither. Therefore noJwill ever be anS<T>.So why doesn’t it invoke your explicit cast operator? I think the answer is in the C# spec, as described in this SO post.
6.4.1 Permitted user-defined conversions
C# permits only certain user-defined conversions to be declared. In particular, it is not possible to redefine an already existing implicit or explicit conversion.
For a given source type S and target type T, if S or T are nullable types, let S0 and T0 refer to their underlying types, otherwise S0 and T0 are equal to S and T respectively. A class or struct is permitted to declare a conversion from a source type S to a target type T only if all of the following are true:
So if I’m reading that right, because
Jis an interface, it is not recognized as a candidate for your explicit cast operator.