Bit masking a byte with an enum

J

Jim H

I have an enum that is derived from byte and a member that is of type byte.
The compiler complains when I try to OR the one of the enum values with the
byte. Why?

[Flags]
public enum eDataPosition : byte
{
ePosition1 = 0x08, //00 001 000
ePosition2 = 0x10, //00 010 000
ePosition3 = 0x18, //00 011 000
ePosition4 = 0x20, //00 100 000
ePosition5 = 0x28, //00 101 000
MASK = 0x38 //00 111 000
};

public byte m_BitMask = 0;

public eDataPosition DataPosition
{
get { return (eDataPosition)(m_PacketMask | eDataPosition.MASK); }
set { m_PacketMask |= value; }
}


I get the following errors:

Operator '|' cannot be applied to operands of type 'byte' and
'TestInterface.Test.eDataPosition'
Cannot implicitly convert type 'TestInterface.Test.eDataPosition' to 'byte'
Operator '|=' cannot be applied to operands of type 'byte' and
'TestInterface.Test.eDataPosition'


I know I can cast them back and forth but why do I have to?
I tried it with and without the "Flags" attribute and with and without the
byte base-type. I get the same errors either way.

Thanks,
jim
 
S

Stoitcho Goutsev \(100\) [C# MVP]

Hi Jim,

There is no implicit conversion between enum objects and their base type.
Flags attribute doesn't help either it is only used by ToString method. If
you need byte flages my suggestion is to use byte constants or declare
m_BitMask to be of type eDataPosition

eDataPosition m_BitMask = (eDataPosition) XXX;

in the case of zero you can write
eDataPosition m_BitMask = 0;
 
N

nal

Well..eDataPosition is a distinct enum value type, The current C# spec says
an explicit conversion is required between an enum type and an integral
type.

So even if the eDataPosition's integral type is byte, you still have to use
an explicit cast. Clear as mud? :)
 
J

Jim H

Thanks to both of you. That explains it. I thought the enum was deriving
from type byte so byte would be its base. I now realize that byte is just
it's integral type and not base.

Thanks again for the quick responses.

jim
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top