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

  • A+
Category:Languages

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.

 


! 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 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: