2

I know in .NET 4 you can use HasFlag

Is there any alternative to the following in .NET 3.5?

if ((enumVar & EnumType.ValueOne) == EnumType.ValueOne)
{
  // someMethod(1) or someMethod(EnumType.ValueOne)
}
if ((enumVar & EnumType.ValueTwo) == EnumType.ValueTwo)
{
  // someMethod(2) or someMethod(EnumType.ValueTwo)
}
if ((enumVar & EnumType.ValueThree) == EnumType.ValueThree)
{
  // someMethod(3) or someMethod(EnumType.ValueThree)
}
if ((enumVar & EnumType.ValueFour) == EnumType.ValueFour)
{
  // someMethod(4) or someMethod(EnumType.ValueFour)
}

...etc for each value in the enum? You must be able to use a for..each loop to accomplish this where the argument to someMethod is the index of the loop?

[Flags]
enum EnumType
{
  ValueOne = 1
  , ValueTwo = 2
  , ValueThree = 4
  , ValueFour = 8
}

EDIT: Only worth looking at the accepted answer, the rest of the comments/answers can be safely ignored.

Greg Tarr
  • 496
  • 3
  • 5
  • 19

4 Answers4

5

You should be able to write something like this. You can make it generic if you want, but there's no way to set the constraint to be enum, so you'd have to check that yourself with reflection.

public static bool HasFlag(YourEnum source, YourEnum flag)
{
    return (source & flag) == flag;
}
Honza Brestan
  • 10,637
  • 2
  • 32
  • 43
  • 2
    shame about that, I guess its why hasFlag was introduced – Greg Tarr Jan 21 '13 at 15:49
  • 2
    @GregT If you "cheat", you can constrain to an enum. See [another answer in another thread](http://stackoverflow.com/a/1409873/1336654) where the project Unconstrained Melody is linked. – Jeppe Stig Nielsen Jan 21 '13 at 21:52
3
foreach (EnumType enumType in Enum.GetValues(typeof(EnumType)))
{
    if(enumVar.HasFlag(enumType)) 
    {
        Console.WriteLine(enumTpye.ToString());
    }
}
Matt
  • 1,648
  • 12
  • 22
0

You can do something like this to do a foreach loop of EnumType

foreach (EnumType enumType in Enum.GetValues(typeof(EnumType)))
{
    if (enumType.HasFlag(enumType))
    {
        Console.WriteLine(enumType.ToString());
    }
}

This will return ValueOne, ValueTwo, ValueThree.. etch not sure if this is what you are looking for please test and let me as well as others know

MethodMan
  • 18,625
  • 6
  • 34
  • 52
0
switch enumvar
{
case valueOne:
{
//do some thing
breake;
}
case valuetwo:
{
//do some thing else
break;
}
default:
break;
    }
Maghraby
  • 11
  • 1