I have the following code:
[Flags()]
public enum Foo
{
Unknown = 0x00,
A = 0x01,
B = 0x02,
C = 0x04,
D = 0x08,
}
public static class Extensions
{
public static List<Foo> AsList(this Foo types)
{
List<Foo> list = new List<Foo>();
foreach(Foo sT in Enum.GetValues(typeof(Foo)))
{
if ((sT & types) == sT) list.Add(sT);
}
return list;
}
}
class Program
{
static void Main(string[] args)
{
Foo foo1 = Foo.A | Foo.B | Foo.C;
Foo foo2 = Foo.C | Foo.B;
Foo firstInfoo1 = foo1.AsList()[0];
Foo firstInFoo2 = foo2.AsList()[0];
}
}
Now firstInfoo1 and firstInfoo2 both come out be Unknown which i don't want. Seeing the code that is there should i return the index [1] always, as so : foo1.AsList()[1]?
Is that a good idea?? Any ideas on the error, bound checking that would need to be done.
Also lets have a look at foo2, i added Foo.C first and Foo.B second. Is there any way i can get from AsList Foo.C and not Foo.B, i.e. the first in order they were added.
Is that possible?
Appreciate the help.
Thanks
Either remove the Unknown value, or do this:
if ((int)sT != 0 && (sT & types) == sT) list.Add(sT);
A little background: those OR-ed enums are not stored like that in memory, they are stored as a simple integer number, so .NET doesn't known how that enum was constructed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With