36

I'm just wondering if anyone knows the reason why you are not allowed to use interfaces with the implicit or explicit operators?

E.g. this raises compile time error:

public static explicit operator MyPlayer(IPlayer player)
{
 ...
}

"user-defined conversions to or from an interface are not allowed"

Thanks,

theburningmonk
  • 15,701
  • 14
  • 61
  • 104
  • The simplest approach is, well, just implement the interface for your concrete class :) Also see http://stackoverflow.com/questions/308986/user-defined-conversion-to-interface – nawfal Apr 20 '13 at 11:59
  • let's begin that neither `public` nor `static` are allowed in interface member definitions.. – quetzalcoatl Apr 26 '13 at 09:55

1 Answers1

43

Section 10.9.3 of the C# spec spells this out. The short version is that it's disallowed so that the user can be certain that conversions between reference types and interfaces succeed if and only if the reference type actually implements that interface, and that when that conversion takes place that the same object is actually being referenced.

Defining an implicit or explicit conversion between reference types gives the user the expectation that there will be a change in reference; after all, the same reference cannot be both types. On the other hand, the user does not have the same expectation for conversions between reference types and interface types.

User-defined conversions are not allowed to convert from or to interface-types. In particular, this restriction ensures that no user-defined transformations occur when converting to an interface-type, and that a conversion to an interface-type succeeds only if the object being converted actually implements the specified interface-type.

Adam Robinson
  • 182,639
  • 35
  • 285
  • 343
  • "Defining an implicit or explicit conversion between reference types gives the user the expectation that there will be a change in reference" great explanation! – jorgebg Oct 02 '17 at 14:53
  • 26
    That explains why the language design team prevented implicit conversions _to_ interface types. Do you know why they additionally decided to restrict conversions _from_ interface types? Was it just for symmetry? – Benjamin Hodgson Nov 14 '17 at 14:11
  • 3
    Yeah, inability to type cast from an interface to a strict type is a really annoying missing feature. Especially for something like JSON.NET where it's going to try to cast it and you basically can't, because C# doesn't allow user-defined conversion of a deserialized interface to a concrete type. – Triynko Apr 07 '20 at 04:02