Search code examples
c#enumsvisual-studio-2008.net-3.5enumeration

Enumeration issue when using Flag attribute


I have below enumeration:

[Flags]
public enum ElementsTag
{
    None,
    Surname,
    SecondSurname,
    Forenames,
    PersonalNumber,
    Birthday,
    Nationality,
    DocumentExpirationDate,
    DocumentNumber,
    Sex,
    CityOfBirth,
    ProvinceOfBirth,
    ParentsName,
    PlaceOfResidence,
    CityOfResidence,
    ProvinceOfResidence
}

So, when I am trying to pass an enumeration value to a method as a parameter like below:

this.GetDataElementFromByteArray((byte[])aData, ElementsTag.ParentsName);

I can see in debug that ElementsTag.ParentsName contains value:

PersonalNumber | DocumentNumber 

Instead of containing only ParentsName. It also happens with other members of the enumeration, for example, passing to the method ElementsTag.Nationality contains:

Nationality = SecondSurname | PersonalNumber

Why?

I would like each enumeration member to contain only its own value and no others, for example:

ElementsTag.ParentsName = ParentsName
ElementsTag.Nationality = Nationality

How to do this?


Solution

  • Your enum definition is equal the this one

    [Flags]
    public enum ElementsTag
    {
        None = 0,
        Surname = 1,
        SecondSurname = 2,
        Forenames = 3,
        PersonalNumber = 4,
        Birthday = 5,
        Nationality = 6,
        DocumentExpirationDate = 7,
        DocumentNumber = 8,
        Sex = 9,
        CityOfBirth = 10,
        ProvinceOfBirth  = 11,
        ParentsName = 12,
        PlaceOfResidence = 13,
        CityOfResidence = 14,
        ProvinceOfResidence = 15
    }
    

    If you pass ElementsTag.ParentsName, the value 12 is used. In binary notation 12 = 0000 1100. Therefore the 3rd and 4th bit is set. The 3rd bit correspond the the value 4, which is ElementsTag.PersonalNumber and the 4th bit is the value 8 which correspond to ElementsTag.DocumentNumber.

    If you want distinctive values, you must use 2^n values like so:

    [Flags]
    public enum ElementsTag
    {
        None = 0,
        Surname         = 1,
        SecondSurname   = 1 << 1, // 2
        Forenames       = 1 << 2,  // 4
        PersonalNumber  = 1 << 3, // 8
        Birthday        = 1 << 4,
        Nationality     = 1 << 5,
        DocumentExpirationDate = 1 << 6,
        DocumentNumber         = 1 << 7,
        Sex                    = 1 << 8,
        CityOfBirth            = 1 << 9,
        ProvinceOfBirth        = 1 << 10,
        ParentsName            = 1 << 11,
        PlaceOfResidence       = 1 << 12,
        CityOfResidence        = 1 << 13,
        ProvinceOfResidence    = 1 << 14
    }