3

I have the following implicit conversion operator:

public static implicit operator InputArgument<T>(T value)
{
   return new InputArgument<T>(value);
}

The following is code in an ASP.NET MVC controller:

This works:

InputArgument<string> input = "Something";

This works:

InputArgument<Controller> input = this;

This works:

InputArgument<IPrincipal> input = new InputArgument<IPrincipal>(User);

But this doesn't work:

InputArgument<IPrincipal> input = User;

The last example gives the error:

> Cannot implicitly convert type
> 'System.Security.Principal.IPrincipal' to
> 'Engine.InputArgument<System.Security.Principal.IPrincipal>'. An
> explicit conversion exists (are you missing a cast?)

What could be the reason that this implicit conversion does not work for IPrincipal?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Gerald
  • 23,011
  • 10
  • 73
  • 102
  • Does this work: InputArgument input = (IPrinciple) User; ? – Martijn van Put Jul 29 '13 at 18:04
  • Nope, tried that, same error. – Gerald Jul 29 '13 at 18:06
  • 2
    possible duplicate of [implicit operator using interfaces](http://stackoverflow.com/questions/143485/implicit-operator-using-interfaces) - that question gives the reason of "it's in the language specification", but doesn't really explain why. [The question it links to](http://stackoverflow.com/questions/9229928/more-on-implicit-conversion-operators-and-interfaces-in-c-sharp-again) goes into a little more depth. – Joe Enos Jul 29 '13 at 18:08
  • Can you share the piece of code that defines the InputArgument class? And what version of the .NET Framework are you using? – pnvn Jul 29 '13 at 18:09
  • Oops, I didn't do a very good job of searching. – Gerald Jul 29 '13 at 18:13
  • Can you share your answer anyways? – obesechicken13 Dec 24 '13 at 08:33
  • Well, the answer is that it doesn't work because it is specified that implicit conversions should not work with interface types. See Eric Lippert's answer below. I'm not entirely satisfied with the reasoning, but I suspect the language design decision stemmed from real-world experience, and the details may be over my head, and it's ultimately not that important to me, so I just do without :) – Gerald Dec 24 '13 at 08:46

1 Answers1

3

User-defined conversions are specified as not working on interfaces. If they did work on interfaces like this then you could end up in a situation where Bar<IFoo> is converted to IFoo via a representation-changing user-defined conversion when the object actually implements IFoo, which would be surprising.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067