Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implicit conversion from generic interface type [duplicate]

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?

like image 279
Gerald Avatar asked Sep 11 '26 13:09

Gerald


1 Answers

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.

like image 75
Eric Lippert Avatar answered Sep 13 '26 03:09

Eric Lippert