0

I was trying to add multiple enum values to a variable based on conditions. For example, I have something like this:

SharedAccessBlobPermissions t = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Read;

if user has chosen other available enum values on the UI, i want to add them was well. But it looks like we can only write it on one line and can't add multiple values later on.

Any idea how can I achieve this?

[Update] Based on the answers, this is what I wrote

var t= new SharedAccessBlobPermissions();
        if (isAllowRead)
        {
            t = SharedAccessBlobPermissions.Read;
        }
        if (isAllowWrite)
        {
            t |= SharedAccessBlobPermissions.Write;
        }
Amit
  • 25,106
  • 25
  • 75
  • 116
  • Just add more values, concatenate them by `|`, you can break it to multilines until you end all by a `;` – King King Dec 02 '13 at 05:46

3 Answers3

3

If SharedAccessBlobPermissions has been declared with [Flags] attribute you can do some set arithemtics. If initially

  SharedAccessBlobPermissions t = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Read;

Addtion:

  // Add SharedAccessBlobPermissions.Delete and SharedAccessBlobPermissions.Clear 
  t |= SharedAccessBlobPermissions.Delete | SharedAccessBlobPermissions.Clear;

Subtraction:

  // Remove SharedAccessBlobPermissions.Delete
  t = (t | SharedAccessBlobPermissions.Delete) ^ SharedAccessBlobPermissions.Delete;
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
1

You can keep adding more values to the bitmask by bitwise-oring them with the current value:

t |= SharedAccessBlobPermissions.AnotherOption
Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
1

You need to use Flags attribute. See the following example:

[Flags]
enum DaysOfWeek
{
   Sunday = 1,
   Monday = 2,
   Tuesday = 4,
   Wednesday = 8,
   Thursday = 16,
   Friday = 32,
   Saturday = 64
}

public void RunOnDays(DaysOfWeek days)
{
   bool isTuesdaySet = (days & DaysOfWeek.Tuesday) == DaysOfWeek.Tuesday;

   if (isTuesdaySet)
      //...
   // Do your work here..
}

public void CallMethodWithTuesdayAndThursday()
{
    this.RunOnDays(DaysOfWeek.Tuesday | DaysOfWeek.Thursday);
}

I suggest you to read the following Thread

Here is another useful answer

Community
  • 1
  • 1
Ofir
  • 5,049
  • 5
  • 36
  • 61