Skip to main content
3 of 6
Provide an example so there is some context about the type.
christo8989
  • 467
  • 3
  • 9
  • 16

Bitmask type to perform binary operations

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

  1. Is the type a struct or class?
  2. Is the type generic or are certain methods generic?
  3. Is it okay to constrain the generics to struct, IConvertible?
  4. 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;  
    }   
}

(I couldn't find a good tag for this question and my rep is not high enough to create one.)

christo8989
  • 467
  • 3
  • 9
  • 16