Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do enum permissions often have 0, 1, 2, 4 values?

Why are people always using enum values like 0, 1, 2, 4, 8 and not 0, 1, 2, 3, 4?

Has this something to do with bit operations, etc.?

I would really appreciate a small sample snippet on how this is used correctly :)

[Flags]
public enum Permissions
{
    None   = 0,
    Read   = 1,
    Write  = 2,
    Delete = 4
}
like image 864
Pascal Avatar asked Oct 01 '22 03:10

Pascal


People also ask

Do enum values start at 0 or 1?

The first member of an enum will be 0, and the value of each successive enum member is increased by 1. You can assign different values to enum member. A change in the default value of an enum member will automatically assign incremental values to the other members sequentially.

Can 2 enums have the same value?

Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

What is enum default value?

The default value for an enum is zero. If an enum does not define an item with a value of zero, its default value will be zero.

Should enums be numbers?

Enums are always assigned numeric values when they are stored. The first value always takes the numeric value of 0, while the other values in the enum are incremented by 1.


1 Answers

Because they are powers of two and I can do this:

var permissions = Permissions.Read | Permissions.Write;

And perhaps later...

if( (permissions & Permissions.Write) == Permissions.Write )
{
    // we have write access
}

It is a bit field, where each set bit corresponds to some permission (or whatever the enumerated value logically corresponds to). If these were defined as 1, 2, 3, ... you would not be able to use bitwise operators in this fashion and get meaningful results. To delve deeper...

Permissions.Read   == 1 == 00000001
Permissions.Write  == 2 == 00000010
Permissions.Delete == 4 == 00000100

Notice a pattern here? Now if we take my original example, i.e.,

var permissions = Permissions.Read | Permissions.Write;

Then...

permissions == 00000011

See? Both the Read and Write bits are set, and I can check that independently (Also notice that the Delete bit is not set and therefore this value does not convey permission to delete).

It allows one to store multiple flags in a single field of bits.

like image 271
Ed S. Avatar answered Oct 19 '22 23:10

Ed S.