TheDeveloperBlog.com


C# Month and Day Arrays

Date names can be stored in an array. The .NET Framework can programmatically return month and day strings. But it is more efficient to store them in string literals and then simply load the correct strings from the metadata.

String ArrayString Literal

Example. First, in this program the days of the week are numbered zero through six and the months are numbered one through twelve. To accommodate these indexes, we set up two static arrays with the appropriate string literals stored in them.

Static Array

Then, when the client invocation wants to load the correct date string, it can simply pass an integer and the helper methods will return the value. No allocations will take place.

C# program that stores months and days

using System;

class Program
{
    static void Main()
    {
	// Test the DateArrays class.
	Console.WriteLine(DateArrays.GetDay((int)DateTime.Today.DayOfWeek));
	Console.WriteLine(DateArrays.GetMonth(DateTime.Today.Month));
    }
}

static class DateArrays
{
    static string[] _months =
    {
	"",
	"January",
	"February",
	"March",
	"April",
	"May",
	"June",
	"July",
	"August",
	"September",
	"October",
	"November",
	"December"
    };
    static string[] _days =
    {
	"Sunday",
	"Monday",
	"Tuesday",
	"Wednesday",
	"Thursday",
	"Friday",
	"Saturday"
    };

    /// <summary>
    /// Get month (1 = January)
    /// </summary>
    public static string GetMonth(int number)
    {
	return _months[number];
    }

    /// <summary>
    /// Get day (0 = Sunday)
    /// </summary>
    public static string GetDay(int number)
    {
	return _days[number];
    }
}

Output

Sunday
January

This class is fast to start up and won't require any allocations during runtime. The string literals are actually stored in the metadata on the disk and will always be in memory. The operating system does not need to be queried.

Note: The main drawback to this class is that it cannot be changed based on the user's locale.

However: For some applications, such as those with standard requirements, this limitation is desirable.


Summary. In this example class, we stored string literals corresponding to the DateTime integers. This achieves a startup time improvement and memory reduction. It requires no operating system queries.

Further: This class will enable you to make specific changes to the representations of the date strings. This results in more flexibility.