Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator && cannot be applied

Tags:

c#

.net

I am testing an example snippet that I found as an answer on another Question

However the compiler is spitting out this "Operator && cannot be applied to operands of type long and bool". Why does it do this? As I read the code, it says "If mask and permission are greater than 0 return success bool"

Am I reading this wrong?

(Also, no one called it out as a bad example so I expected it to work. Not that I am a copy-paste coder)

bool CheckMask( long Mask, long TestPermission ) {
    return Mask && TestPermission > 0;
}

long mask = 4611686844973976575;

const long MASK_ViewListItems = 0x0000000000000001;
bool HasPermission_ViewListItems = CheckMask(mask, MASK_ViewListItems);
// HasPermission_ViewListItems is true

const long MASK_UseClientIntegration = 0x0000001000000000;
bool HasPermission_UseClientIntegration = CheckMask(mask, MASK_UseClientIntegration);
// HasPermission_UseClientIntegration is false

There are an awful lot of similar questions on StackOverflow and I've clicked through most of them, there's a big list to my right as I type. None have applied to my situation, at least I was able to see the relation between the answers and my problem.

like image 421
negligible Avatar asked Jun 19 '12 14:06

negligible


1 Answers

You're using && (conditional AND, only valid for bool operands) instead of & (bitwise AND, valid for bool operands or integer operands) - I suspect you want the latter, and you should also use brackets due to precedence rules. I'd change the parameter names to follow .NET naming conventions, too - and make it static as it doesn't rely on any state:

static bool CheckMask(long mask, long testPermission)
{
    return (mask & testPermission) > 0;
}

You might also want to change to using an enum instead of long:

[Flags]
public enum Permissions
{
    ViewListItems = 1 << 0,
    ...
    UseClientIntegration = 1 << 9
}

static bool CheckMask(Permissions mask, Permissions testPermission)
{
    return (mask & testPermission) != 0;
}
like image 78
Jon Skeet Avatar answered Oct 13 '22 00:10

Jon Skeet