0
using System;

public class Program
{
    public static void Main()
    {
        T<A> g = new T<A>();
        T2 g = new T2();
    }
}

public class T<A>
{
    public static extern implicit operator T<A> (A v);
}

public class T2
{
    public static extern implicit operator T2 (A v);
}

public interface A{}

Fiddle

The code only works with T of A. With T2 it gives the error "Compilation error (line 19, col 26): T2.implicit operator T2(A): user-defined conversions to or from an interface are not allowed", why is it allowed with generics? Are there any limitations to using generics as a workaround?

This question is not a duplicate of this question because this question is asking why it is allowed with generics and if there are any limitations to this workaround not why user-defined conversions to and from interfaces are not allowed.

trinalbadger587
  • 1,905
  • 1
  • 18
  • 36
  • 2
    You're not using the conversion at all in `Main` - what doesn't work in the code you've given? Your question is very unclear... (And is `extern` relevant here? If not, I'd remove it... basically, reduce this to a minimal example.) – Jon Skeet Jun 03 '17 at 21:05
  • Possible duplicate of [Why isn't it possible to define implicit cast operator from interface to class?](https://stackoverflow.com/questions/12533748/why-isnt-it-possible-to-define-implicit-cast-operator-from-interface-to-class) – Sir Rufo Jun 03 '17 at 21:15
  • The extern isn't relevant but that way I don't have to define a function body. – trinalbadger587 Jun 04 '17 at 06:15

1 Answers1

2

Actually both would not work, however you have re-defined A in your T<A> class to be a generic parameter. If you rename your class to T<B> and use B in the approprate spots it will give you the same error for the generic conversion.

public class T<B>
{
    public static extern implicit operator T<B> (A v);
}

gives the error

Compilation error (line 14, col 26): T<B>.implicit operator T<B>(A): user-defined conversions to or from an interface are not allowed

The problem you are having has nothing to do with generics and is instead caused by the fact that you are trying to do a implicit conversion from a interface. If you switched A to a class instead of a interface both methods would work.

using System;

public class Program
{
    public static void Main()
    {
        T<A> g = new T<A>();
        T2 g2 = new T2();
    }
}

public class T<B>
{
    public static extern implicit operator T<B> (A v);
}

public class T2
{
    public static extern implicit operator T2 (A v);
}

public class A{}
Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431