Compiler Error CS0034
Operator 'operator' is ambiguous on operands of type 'type1' and 'type2'
An operator was used on two objects and the compiler found more than one conversion. Because conversions have to be unique, you either have to make a cast or to make one of the conversions explicit. For more information, see Conversion Operators (C# Programming Guide).
The following sample generates CS0034:
// CS0034.cs
public class A
{
// allows for the conversion of A object to int
public static implicit operator int (A s)
{
return 0;
}
public static implicit operator string (A i)
{
return null;
}
}
public class B
{
public static implicit operator int (B s)
// one way to resolve this CS0034 is to make one conversion explicit
// public static explicit operator int (B s)
{
return 0;
}
public static implicit operator string (B i)
{
return null;
}
public static implicit operator B (string i)
{
return null;
}
public static implicit operator B (int i)
{
return null;
}
}
public class C
{
public static void Main ()
{
A a = new A();
B b = new B();
b = b + a; // CS0034
// another way to resolve this CS0034 is to make a cast
// b = b + (int)a;
}
}
In C# 1.1 a compiler bug made it possible to define a class that has implicit user-defined conversions to both int and bool, and to use a bitwise AND operator (&) on objects of that type. In C# 2.0, this bug was fixed to bring the compiler into compliance with the C# specification, and therefore the following code will now cause CS0034:
namespace CS0034
{
class TestClass2
{
public void Test()
{
TestClass o1 = new TestClass();
TestClass o2 = new TestClass();
TestClass o3 = o1 & o2; //CS0034
}
}
class TestClass
{
public static implicit operator int(TestClass o)
{
return 1;
}
public static implicit operator TestClass(int v)
{
return new TestClass();
}
public static implicit operator bool(TestClass o)
{
return true;
}
}
}