agnete
agnete

Reputation: 13

How can I use bitwise OR on an enum and an int?

I have a flag Enum called Role and an extension method called AddRole, that takes a Role enum and an int that works like a flag and only contains ones and zeros, where each 1 represents a role that a person has. I want the method to add the role to the int, so that AddRole(Role.Grandmother, 1000) returns 1100 for instance.

[Flags]
public enum Role
    {
        Mother = 1,
        Daughter = 2,
        Grandmother = 4,
        Sister = 8,

    }

I tried doing this:

public static int AddRole(this Role newRole, int currentRoles)
        {
            return (int)((Role)currentRoles | newRole);
        }

but this just returns 1004. Does anyone know the right way to do this? (I have no way of avoiding the "binary ish" int representation, as this is the way the entity is stored in the (very old and untouchable) database)

Upvotes: 1

Views: 406

Answers (1)

René Vogt
René Vogt

Reputation: 43946

So the actual issue you have is how to interprete a decimal value (like 1000) as a binary representation.

You can do this by converting it to a string and then let Convert.ToInt32() overload that takes a base argument parse it again as a binary value:

int i = 1000;
int b = Convert.ToInt32(i.ToString(), 2); // interprete the string as a binary value
// b = 8

Upvotes: 3

Related Questions