Operator '!' cannot be applied to operand of type x

Viewed 1161

So I have some code in VB that I am trying to convert to C#. This code was written by someone else and I am trying to understand it but with some difficulty. I have some bitwise operator and enum comparison to do but keep throwing an error out:

I cannot say that i have used a lot of these syntaxes before and am baffled how to write this code. I have used Google to understand more about it and also used VB to C# online converters in the hopes of getting some basic guidance but nothing. The code below

VB - This is the original code that works

Flags = Flags And Not MyEnum.Value ' Flags is of type int

C# -the code I converted which is throwing an error

Flags = Flags & !MyEnum.Value; // Flags is of type int

Error - The error that is returned every time

Operator '!' cannot be applied to operand of type MyEnum'.

Any help and some explanation on this will be greatly appreciated.

3 Answers

! can only operate on bool type. You seem to be operating on some bit flags. In that case you should use the bitwise NOT operator ~ instead of the logical NOT operator !:

Flags = Flags & ~((int)MyEnum.Value); // you need to cast to int as well

To get the best conversion, it helps to first understand the implicit conversion that VB is doing for you:

Flags = Flags And Not (CInt(MyEnum.Value))

This is equivalent to the C# code:

Flags = Flags & ~(int)MyEnum.Value;

Which can be shortened:

Flags &= ~(int)MyEnum.Value;

In VB, "Not" is both the logical and bitwise operator, depending on context, but in C# you have two distinct operators.

You maybe confusing Logical and Bitwise unary operators

Lets visit the help

Operators (C# Programming Guide)

Unary Operators

  • +x Identity
  • -x Negation
  • !x Logical negation
  • ~x Bitwise negation
  • ++x Pre-increment
  • --x Pre-decrement
  • (T)x Explicitly convert x to type T

Compiler Error CS0023

Operator 'operator' cannot be applied to operand of type 'type'

An attempt was made to apply an operator to a variable whose type was not designed to work with the operator.

Related