- Home /
Can't compare byte to byte?
I would like to use an enum for some bitmask flags, along the lines of:
enum myFlags : byte {
flagOne = 1 << 0,
flagTwo = 1 << 1,
flagThree = 1 << 2
}
And then compare these flags against other byte variables such as:
byte myValue = 1 << 1;
byte someResult = (myValue & myFlags.flagOne);
However I consistently keep running into casting errors. Either "cannot compare type 'byte' and type 'myFlags'", or when I got frustrated and tried:
byte someResult = (myValue & (1 << 0));
I then get "cannot compare type 'byte' and 'int'"
How should one go about this sort of thing in Unity's flavor of C#? I admit, what experience I have with C is all C++, but needing to re-cast all your byte variables to byte every time you try to use them seems ridiculously wrong. What's going on here?
"Unity's flavor of C#": that might be the confusion. C# just doesn't like bytes as much as program$$anonymous$$g languages for adults. I believe 1<<3
is an int. And enums don't enjoy implicits casts to ints/bytes in C# as much as they could.
Just looking at standard C# types and conversion rules should help solve this.
Thanks for pointing me at where to look. Do you happen to know if something like this winds up as an int as well?
byte someValue = 1;
Answer by POiD · Apr 02, 2015 at 02:58 PM
I am comparing bytes against my enums, all you have to do is cast them.
byte testByte = (byte)MyEnum.firstValue;
if (testByte == (byte)MyEnum.secondValue) ....
Works for me in C#.
Answer by DiegoSLTS · Apr 02, 2015 at 03:29 PM
I'm not sure why you want things to be bytes, but even if you define the enum to be a bytes enum, the conversion is never implicit, you have to cast the value if you want to assign it to a byte variable.
Anyway, I'd do it differently. First, for enums intended do be used as flags you can use the Flags attribute: http://www.dotnetperls.com/enum-flags
This way you can have a variable of the type of the enum that holds many values of the enum, just like a byte of flags.
And with that enum defined you don't need a byte variable, you can just have a variable of the enum.
using System;
....
[Flags]
enum myFlags : byte {
flagOne = 1 << 0,
flagTwo = 1 << 1,
flagThree = 1 << 2
}
And when you want to use it:
myFlags myValue = myFlags.flagOne | myFlags.flagTwo;
Debug.Log (myValue); // "flagOne, flagTwo"
myFlags someResult = myValue & myFlags.flagOne;
Debug.Log (someResult); // "flagOne"
myFlags otherResult = myValue & myFlags.flagThree;
Debug.Log (otherResult); // "0"