Royi Namir
Royi Namir

Reputation: 148524

Enhance C# Enum in order to use Bitwise operation?

binary operation are very useful . this way I can do | ^ & in order ro emit a new sequence.

However , sometimes there are Enum's which doesnt have a base 2 values attached to it (or value at all).

ie:

enter image description here

I would like to Enhance || derive|| attach values to the Enum ( if posssible ) to each entry.

so I will be able to do :

if (MyListItemType== Header |Footer ) ...

is it possible ? or is there any tricky work arounds ?

Upvotes: 1

Views: 1740

Answers (6)

Aliostad
Aliostad

Reputation: 81660

As others have said it cannot be done but I will use a shortcut using Extension methods:

public enum MyEnum
    {
        This,
        That,
        TheOther
    }

    public static class MyEnumeExtensions
    {
        public static bool IsAny(this MyEnum enumValue, params MyEnum[] values)
        {
            return values.Any((e) => e == enumValue);
        }
    }

So I can use:

myEnum.IsAny(This, That);

Which is almost what you wanted to achieve.

Upvotes: 3

Henk Holterman
Henk Holterman

Reputation: 273179

I would like to Enhance || derive|| attach values to the Enum ( if posssible ) to each entry.

You can't do that (short of redefining the enum). But when it is in code you don't own, it's over. There can already exist code that relies on the numbering, changing the int values would break that code.

But this usually means the Enum was not intended to be a bit-set, so trying to use it as one probably isn't a good idea anyway.

It's a design decision for the creator of the code.

Look at your example list:

var item = ListItemType.Header | ListItemType.Footer | ListItemType.SelectedItem;

Can item really be a header, a footer and a selected item at the same time? This is a list of mutually-exclusive options.

Upvotes: 10

Oded
Oded

Reputation: 498942

No, you can't.

If an Enum was not marked with the FlagsEnumeration and/or has the correct bit mask values (as you put it - "doesn't have base2"), you can't use bitwise operations on it to get meaningful results.

Upvotes: 4

Quinton Bernhardt
Quinton Bernhardt

Reputation: 4793

[Flags]
enum Days2
{
    None = 0x0,
    Sunday = 0x1,
    Monday = 0x2,
    Tuesday = 0x4,
    Wednesday = 0x8,
    Thursday = 0x10,
    Friday = 0x20,
    Saturday = 0x40
}

http://msdn.microsoft.com/en-us/library/cc138362.aspx

You can then use bitwise operators on them.

Upvotes: 0

ChriPf
ChriPf

Reputation: 2780

You are looking for Flag Enums: http://msdn.microsoft.com/en-us/library/cc138362.aspx

Upvotes: 0

John Koerner
John Koerner

Reputation: 38079

You want to use a flags enum:

[Flags]
enum Days2
{
    None = 0x0,
    Sunday = 0x1,
    Monday = 0x2,
    Tuesday = 0x4,
    Wednesday = 0x8,
    Thursday = 0x10,
    Friday = 0x20,
    Saturday = 0x40
}
class MyClass
{
    Days2 meetingDays = Days2.Tuesday | Days2.Thursday;
}

Upvotes: 5

Related Questions