Switch on enum value - CSharp Language Basics

CSharp examples for Language Basics:switch

Description

Switch on enum value

Demo Code

using System;/*ww  w  .j ava2 s  .c o m*/
class DaysInMonth
{
   enum Month {January, February, March, April, May, June, July, August, September, October, November, December}
   public static void Main()
   {
      Month currentMonth;
      int year;
      int dayCount = 0;
      Console.Write("Enter year: ");
      year = Convert.ToInt32(Console.ReadLine());
      Console.Write("Enter month: ");
      currentMonth = (Month)Enum.Parse(typeof(Month), Console.ReadLine(), true);
      switch (currentMonth)
      {
         case Month.January:
         case Month.March:
         case Month.May:
         case Month.July:
         case Month.August:
         case Month.October:
         case Month.December:
            dayCount = 31;
            break;
         case Month.April:
         case Month.June:
         case Month.September:
         case Month.November:
            dayCount = 30;
            break;
         case Month.February:
            if (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0))
               dayCount = 29;
            else
               dayCount = 28;
            break;
         default:
            Console.WriteLine("Invalid month");
            break;
      }
      Console.WriteLine("Number of days in {0} of year {1}: {2}", currentMonth, year, dayCount);
   }
}

Result


Related Tutorials