How to loop each items in enum ?

C

cyshao

Hi ,my friends:

I have a enum type ,EMyEnum , defigned as [Flag()].
I just want to do something like this:

foreach( EMyEnum crrEnum in EMyEnum )
{
//do something
}

////////////////////////////////////////////////////
But I can't find any way to do that, and only used a very foolish method
like this

string[] names = Enum.GetNames(typeof(EMyEnum ));
foreach (string crrEnumName in names )
{
EMyEnum crrEnum = (EMyEnum )Enum.Parse( typeof(EMyEnum ) ,
crrEnumName );
//do something
}

///////////////////////////////////////////////////
Are there any good ideas to do that?
Or Microsoft forget to design a method like this:
vector< EMyEnum > Enum.GetTypes( typeof(EMyEnum ) )

Thanks

CYShao ^_^
 
A

Alexander Shirshov

Well, if your method is foolish then I've been posing as a fool hundreds of
times! :)

I routinely use Enum.GetNames to fill a combobox for instance and then
Enum.GetValues to get the selected value. Did you look at GetValues method?
Your sample could be rewritten as:

foreach (EMyEnum val in Enum.GetValues(typeof(EMyEnum)))
{
Console.WriteLine(val);
}


And then there's Reflection of course. Although an overkill in most
enum-related tasks, it allows some neat tricks like working with custom
attributes:

class FriendlyNameAttribute : Attribute
{
public readonly string Value;
public FriendlyNameAttribute(string value)
{
Value = value;
}
}

enum MyEnum {
[FriendlyName("Value of One")]
One,
[FriendlyName("Value of Two")]
Two,
Three
};

class MainClass
{
public static void Main(String[] args)
{
foreach (FieldInfo fi in typeof(MyEnum).GetFields())
{
FriendlyNameAttribute[] names =
(FriendlyNameAttribute[])fi.GetCustomAttributes(typeof(FriendlyNameAttribute),
true);
if (names.Length > 0)
{
Console.WriteLine(names[0].Value);
}
else
{
Console.WriteLine(fi.Name);
}
}
}
}


HTH,
Alexander
 
J

Jon Skeet [C# MVP]

Alexander Shirshov said:
Well, if your method is foolish then I've been posing as a fool hundreds of
times! :)

I don't think so...
I routinely use Enum.GetNames to fill a combobox for instance and then
Enum.GetValues to get the selected value. Did you look at GetValues method?

Your sample could be rewritten as:

foreach (EMyEnum val in Enum.GetValues(typeof(EMyEnum)))
{
Console.WriteLine(val);
}

And that's the difference - I'd expect that calling GetValues is much
cheaper than calling GetNames and then calling Enum.Parse on each name.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top