Saleem
Saleem

Reputation: 145

Not getting expected result from Enum

enum DaysInMonth
    {
        Jan = 31, Feb = 28, Mar = 31, Apr = 30, May = 31, Jun = 30,
        Jul = 31, Aug = 31, Sep = 30, Oct = 31, Nov = 30, Dec = 31
    };
DaysInMonth dm = DaysInMonth.Dec;
        Console.WriteLine($"Number of days in {dm} is {dm:D}");

Getting Number of days in Jul is 31, expecting Number of days in Dec is 31

Upvotes: 0

Views: 61

Answers (2)

UJS
UJS

Reputation: 861

You are trying to Make use of Enum. So Try Following Code .

enum DaysInMonth
        {
            Jan = 31, Feb = 28, Mar = 31, Apr = 30, May = 31, Jun = 30,
            Jul = 31, Aug = 31, Sep = 30, Oct = 31, Nov = 30, Dec = 31
        };



static void Main(string[] args)
        {
            DaysInMonth dm = DaysInMonth.Dec;
            Console.WriteLine("Number of days in {0} is {1} : ", dm, (int)dm);
            Console.ReadKey();
        }

Upvotes: 0

Daniel
Daniel

Reputation: 2804

Its not a good idea to hardcode the number of days in a month. What about leap years?

The correct way to gets days in a month:

DateTime.DaysInMonth(year, month)

Upvotes: 4

Related Questions