Without any specific implementation details, how would you create a bitmask type that wraps binary arithmetic into something easy to read? Ideally, this would be used with an enum, which is why there are some generic methods.
Some Questions
- Is the type a struct or class?
- Is the type generic or are certain methods generic?
- Is it okay to constrain the generics to
struct, IConvertible? - Is a type like this preferred when working with bitmasks?
Starting Example: Here's a fiddle.
//Example Use
var days = new Bitmask((ulong)(Day.Monday | Day.Tuesday));
days.Contains((ulong)Day.Friday); //false
days.Contains((ulong)Day.Monday); //true
//Example Use END
public enum Day { Monday = 1, Tuesday = 2, Wednesday = 4, Thursday = 8, Friday = 16, Saturday = 32, Sunday = 64 }
public struct Bitmask
{
//Bitmask Value
private ulong _value;
public ulong Value
{
get { return _value; }
set { _value = value; }
}
//Constructor
public Bitmask(ulong value) { _value = value; }
//Methods
public bool Any() { return _value != 0; }
public void Clear() { _value = 0; }
public bool Contains(ulong value) { return (_value & value) == value; }
public bool Equals(ulong value) { return _value == value; }
public List<TEnum> ToList<TEnum>() where TEnum : struct, IConvertible
{
var local = this;
var result = ((TEnum[])Enum.GetValues(typeof(TEnum))).Where(m => local.Contains<TEnum>(m)).ToList();
return result;
}
}
Containsdoesn't look right to me:new Bitmask(1).Contains(3)returnstrue. \$\endgroup\$new Bitmask(1).Contains(3)doesn't really make sense so I will add some code to clarify what the type is doing. Also, the fiddle provides some extra details. \$\endgroup\$