Enumerations as Counters

  • Thread starter Thread starter Robert Warnestam
  • Start date Start date
R

Robert Warnestam

Hi,

I've just switched from Delphi to Visual Studio and I'm wondering how to use
enumerations in loops.

In Delphi you declare the enumation as

TMyRole= ( wrSystemNet=1,wrPrivateNet,wrWarnestamNet, wrFamilyTreeNet );

and this can be used in a loop as

role: TMyRole;

for role:=Low(TMyRole) to High(TMyRole) do begin
...
end;

Can this be done in C#?

Thanks

Robert Warnestam
 
It's a bit more long winded, but given an enum defined as:

public enum TestEnum
{
FirstValue,
SecondValue,
ThirdValue,
FourthValue
}

the following code will provide you with a loop on the enum values:
Array values = Enum.GetValues(typeof(TestEnum));
foreach(TestEnum value in values)
{
Console.WriteLine(value.ToString());
}

And will display:

FirstValue
SecondValue
ThirdValue
FourthValue

on the console. HTH
 
Thanks,

That was the code I was looking for. I did some other research and found another solution (bot not so clear).

/Robert



public enum CodabRole {
_Low = 1,
crSystemAdmin = _Low,
crTapUser,
crPreemUser,
crCodabUser,
_High = crCodabUser
}

for ( role = CodabRole._Low; role <= CodabRole._High; role++ )
{
// some code
}
 
I agree, the version you posted is not very clear, but it also has at least two glaring problems:

1) The enum now has two names (_Low and _High) which make no sense to anyone using your enum
2) The enum would have to have contiguous values (you couldn't specifiy crCodabUser = 100 for example)

Cheers

Ed
Thanks,

That was the code I was looking for. I did some other research and found another solution (bot not so clear).

/Robert



public enum CodabRole {
_Low = 1,
crSystemAdmin = _Low,
crTapUser,
crPreemUser,
crCodabUser,
_High = crCodabUser
}

for ( role = CodabRole._Low; role <= CodabRole._High; role++ )
{
// some code
}
 
Back
Top