Enumeration versus array

前端 未结 5 1794
滥情空心
滥情空心 2021-01-16 05:57

I was wondering what would be better: An enumeration declaration or a string array:

enum MonthName{January, February, March, April, May, June, ...)
         


        
5条回答
  •  不思量自难忘°
    2021-01-16 06:26

    Both enum and strings are different in this case and will produce different results. In case of enum you can store month number with month name in a variable of enum type e.g.

    MonthName mn = March;
    

    The variable mn will carry integer value 2. In case of array of strings with month names you need to specify month number as array index and what you'll get is the string name of the month rather the month number e.g.

    string mn = MonthName[2];
    

    The variable mn will carry the string "March" and can be used to display month. However, you can use both enum and string array in a better way e.g.

    string mn = MonthName[March];
    

    Here, enum March will act as index of the string array MonthName and returns the "March".

提交回复
热议问题