SaurabhCooks SaurabhCooks - 1 month ago 14
C# Question

Print weekdays from enum

Being new to programming my question might seem a little basic one, what I want to is to print all the days mentioned in the enum using a loop or otherwise.
I have used a console application for the same. Tips to improve basics of C# language coding capabilities along with the answer will be much appreciated.

using System;

namespace _28_11_2016_enum
{
class Program
{
static void Main(string[] args)
{
weekdays wd = weekdays.mon;

for (int i = 0; i < 7; i++)
{


int a = (int)wd;
a = a + i;
wd = (wd)a;// faulty code.
Console.WriteLine(wd);
}
Console.Read();
}
enum weekdays : int
{
mon, tue, wed, thur, fri, sat, sun
}
}


}

Answer

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 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();
 }
Comments