Edit

Share via


Compiler Error CS0218

The type ('type') must contain declarations of operator true and operator false

If a user-defined type overloads the & operator or | operator, it must also define true and false operators, in order to make short-circuiting && operator or || operator defined.

The following sample generates CS0218:

C#
// CS0218.cs  
using System;  
public class MyClass  
{  
   // uncomment these operator declarations to resolve this CS0218  
   /*  
   public static bool operator true (MyClass f)  
   {  
      return false;  
   }  
  
   public static bool operator false (MyClass f)  
   {  
      return false;  
   }  
   */  
  
   public static implicit operator int(MyClass x)  
   {  
      return 0;  
   }  
  
   public static MyClass operator & (MyClass f1, MyClass f2)  
   {  
      return new MyClass();  
   }  
  
   public static void Main()  
   {  
      MyClass f = new MyClass();  
      int i = f && f;   // CS0218, requires operators true and false  
   }  
}  

See also