0
votes

I have an assignment, I have to get a date and then display it in different formats(MM/DD/YYYY, DD/MM/YYYY, DD of month YYYY and so on...). The months have to be enum and I have to make it in a separate class Date. I tried first turning the enum into strings with a switch but always when I parse the number from the console I get an error. Here is the code:

enum Month { January = 1, Fabruary, March, April, May, June, July,August, September, October,
November, December }

class Date
{
    private int m_Day, m_Year;
    private Month m_Month;
    
    public Date(int day, Month month, int year)
    {
        this.m_Day = day;
        this.m_Month = month;
        this.m_Year = year;
    }
    public void Print()
    {
        string month = "";
        Console.WriteLine(PrintMonth(month));
    }
    public string PrintMonth(string month)
    {
        int x = (int)Month;
        switch (x)
        {
            case 1:
                month = "January";
                break;
            case 2:
                month = "Fabruary";
                break;
            case 3:
                month = "March";
                break;
            case 4:
                month = "April";
                break;
        }
        return month;
    }
    public int Day
    {
        get { return m_Day; }
        set { if(Day>=0&&Day<=31)m_Day = value; }
    }
    public Month Month
    {
        get { return m_Month; }
        set { if (Month >= Month.January && Month <= Month.December)m_Month = value; }
    }
    public int Year
    {
        get { return m_Year; }
        set { m_Year = value; }
    }
}

And that's the Main block

static void Main(string[] args)

  {
        int m_Day=0, m_Year=0;
        Month m_Month=0;
        Date date = new Date(m_Day,m_Month,m_Year);
        int month = int.Parse(Console.ReadLine());
        m_Month = (Month)month;
        date.PrintMonth(m_Month);
    }
2
What is the error exactly? On which line?Soner Gönül
It says that the error is on this line date.PrintMonth(m_Month);user3144416
That method takes a string. You're giving it an enum.Jordi Vermeulen

2 Answers

1
votes

You just have to write the enum value:

enum Month
{
    January=1,
    February=2
}
static void Main(string[] args)
{
    Console.WriteLine(((Month)1));
}

So your PrintMonth can take an int or a Month value, a ToString() of an enum returns its string representation.

0
votes
  m_Month = (Month)month;
        date.PrintMonth(m_Month.ToString());

But its not proper way of implementation. You should be using Enum.Parse or Enum.TryParse and using (int)Enum to get integer value and Enum.ToString() to get the string value