Export (0) Print
Expand All
Expand Minimize

Compiler Error CS0457

Ambiguous user defined conversions 'Conversion method name 1' and 'Conversion method name 2' when converting from 'type name 1' to 'type name 2'

Two conversion methods are applicable, and the compiler is unable to decide which one to use.

One scenario that can cause this error is as follows:

  • You want to convert class A to class B where A and B are unrelated.

  • A is derived from A0, and there is a method that converts from A0 to B.

  • B has a subclass B1 and there is a method that converts from A to B1.

The compiler will weight the two conversion methods equally, because the first conversion provides the best destination type, and the second conversion provides the best source type. Since the compiler will be unable to choose, this error will be generated. To resolve, write a new explicit method converting A to B.

Another scenario that causes this error is if there are two methods that convert A to B. To fix, specify which conversion to use through an explicit cast.

The following sample generates CS0457.

// CS0457.cs
using System;
public class A { }

public class G0 {  }
public class G1<R> : G0 {  }

public class H0 {
   public static implicit operator G0(H0 h) {
      return new G0();
   }
}
public class H1<R> : H0 {
   public static implicit operator G1<R>(H1<R> h) {
      return new G1<R>();
   }
}

public class Test 
{
   public static void F0(G0 g) {  }
   public static void Main() 
   {
      H1<A> h1a = new H1<A>();
      F0(h1a);   // CS0457
   }
}

Community Additions

ADD
Show:
© 2014 Microsoft