You don't have to loop - Enum.GetNames
returns the names, and string.Join
concat them together into a single string
:
// mon, tue, wed, thur, fri, sat, sun
Console.Write(string.Join(", ", Enum.GetNames(typeof(weekdays))));
in case you want int
values:
// 0, 1, 2, 3, 4, 5, 6
Console.Write(string.Join(", ", Enum.GetValues(typeof(weekdays)).Cast<int>()));
Edit: if you insist on loop I suggest foreach one:
// mon == 0 ... sun == 6
foreach (var item in Enum.GetValues(typeof(weekdays))) {
Console.WriteLine($"{item} == {(int) item}");
}
In case of for loop
// do not use magic numbers - 0..7 but actual values weekdays.mon..weekdays.sun
for (weekdays item = weekdays.mon; item <= weekdays.sun; ++item) {
Console.WriteLine($"{item} == {(int) item}");
}
However, in real world applications, please, use standard DayOfWeek enum
.
Edit 2: your own code (in the question) improved:
static void Main(string[] args) {
for (int i = 0; i < 7; i++) { // do not use magic numbers: what does, say, 5 stand for?
// we want weekdays, not int to be printed out
weekdays wd = (weekdays) i;
Console.WriteLine(wd);
}
Console.Read();
}
Edit 3: your own code (in the answer) improved:
// you have to do it just once, that's why pull the line off the loop
string[] s = Enum.GetNames(typeof(weekdays));
// do not use magic numbers - 7: what does "7" stands for? -
// but actual value: s.Length - we want to print out all the items
// of "s", i.e. from 0 up to s.Length
for (int i = 0; i < s.Length; i++)
Console.WriteLine(s[i]);