Fun with enum bitflags
I've previously learned about the enum [Flags()]
attribute, but had forgotten usage and reference to it isn't the best, so i figured, iput this down before it slips my mind again.
Say you want a compact way to store a bunch of boolean flags but you want it to end up as human readable code and you don't want to deal with binary operations. Step 1) use an enum for your flags and give the enum the [Flags()]
attribute. Now you have a human readable flags, but you still have to do bitwise operations on them to set, unset and get these flags. So, wrap the whole thing in a struct giving a boolean property as accessor for each flag.
struct ByteFlag
{
// Internal storage of our flags -----------------------------
[Flags()]
enum flags : byte
{
IsCool = 1,
IsTasty = 2
}
flags bf;
// Initialize, set and retrieve the underlying storage ------
public byter(byte pInit)
{
bf = (byteFlag)pInit;
}
public byte ToByte()
{
return (byte)bf;
}
public void FromByte(byte pValue)
{
bf = (byteFlag)pValue;
}
// Accessors ------------------------------------------------
public bool IsCool
{
get { return (bf&byteFlag.IsCool)==byteFlag.IsCool; }
set { bf = (value)?bf|byteFlag.IsCool:bf&~byteFlag.IsCool; }
}
public bool IsTasty
{
get { return (bf&byteFlag.IsTasty)==byteFlag.IsTasty; }
set { bf = (value)?bf|byteFlag.IsTasty:bf&~byteFlag.IsTasty; }
}
}
Now you can do store that flag in a byte and when you want to manipulate the flags it's as simple as: