0

What's the best way of providing toggles to a function call in c# ? similar to how it is done in C/C++. I want to be able to add additional toggles without breaking the API. The ideal solution requires the least LOC.

E.g., in C we can do FILE_OPEN | FILE_READONLY.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Hassan Syed
  • 20,075
  • 11
  • 87
  • 171

2 Answers2

2

You mean using Flags Enum? Here is a little tutorial with snippets: http://www.dotnetperls.com/enum-flags Example:

class Program
{

    [Flags]
    public enum MyFlags
    {
        Foo = 0x1,
        Bar = 0x2,
        Baz = 0x4
    }

    static void Main(string[] args)
    {
        MyFlags fooBar = MyFlags.Foo | MyFlags.Bar;

        if (fooBar.HasFlag(MyFlags.Foo))
            Console.WriteLine("Item has Foo flag set");
    }
}
Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98
1

Whilst you can use flags enum, I personally find that using bitwise operators for set operations is somewhat unclean. You could use HashSet<MyEnum>. Add members to the set with Add, and test for membership with Contains.

But it still makes for a mess at the call site. This is one area where C# is weak in comparison with many other languages. Ideally there should be a set type built into the language that supported an in operator to test for membership.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • I didn't want to do something like that, that is introducing a dynamic construct to solve a compile time problem. It is quite robust though. +1. – Hassan Syed Jan 16 '13 at 13:51