views:

484

answers:

2

I have to fill a combobox with month in English: January, February, etc. I did it next way:

private string[] AmericanMonths
{
  get
  {
    var arr = new string[12];
    var americanCulture = new CultureInfo("en-US");
    for (int i = 0; i < 12; i++)
    {
      arr[i] = new DateTime(2000, i + 1, 1).ToString("MMMM", americanCulture);
    }
    return arr;
  }
}

comboMonth.Items.AddRange(AmericanMonths);

How do you think, what way is better (perfomance)?

Is there a way to convert an integer representing month number to it's name?

+11  A: 

The CultureInfo already contains the list of month names right in the framework. You could just write:

var americanCulture = new CultureInfo("en-US");
comboMonth.Items.AddRange(americanCulture.DateTimeFormat.MonthNames.Take(12)); //to remove last empty element
Jose Basilio
+1 for the use of a descriptive variable name to make the code 'self-documenting'!
Matt Hamilton
Thanks! An how do you think, what is the best way to remove last empty item in that array? I found only ToList(); RemoveAt(length - 1); ToArray()
abatishchev
This should do it: americanCulture.DateTimeFormat.MonthNames.Take(12)
Jose Basilio
+1 also for better performing solution.I did 100000 iterations of original and your solution.00:02.59 - Original solution00:02.03 - Jose Basilio's solution.
Vadim
+2  A: 

CultureInfo has DateTimeFormat property which contains the information about the date time formatting. From there you can use GetMonthName or GetAbbreviatedMonthName. Or alternatively you can get the array of month names through the MonthNames property of the DateTimeFormatInfo.

Mikko Rantanen