HomeSearch

C# Month, Day Arrays

This C# example program uses arrays of strings containing month and day names.
Month, 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. 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 we want to load the correct date string, we can pass an integer and the helper methods will return the value.

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

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
Notes, runtime. Once initialized, this class will not 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.DateTime
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls