Why Can’t I Use My Own Calendar Classes In Custom Cultures ?

In Tuesday’s webcast on Custom Cultures I was asked a very interesting questions about creating a Hindi Calendar for use with a custom culture. My answer was a bit misleading because I was focussing on the problem of how to create a calendar which had quite different rules to most other calendars and I forgot the simple truth which is that you can’t use custom calendars in custom cultures. Here’s why.

The Problem

It is possible to create your own Calendar classes by inheriting from the Calendar class and then implementing all of the Calendar classes’ abstract members. The problem is that when you attempt to assign this new Calendar to the DateTimeFormatInfo.Calendar property an InvalidOperationException is thrown:-

DateTimeFormatInfo dateTimeFormatInfo = new DateTimeFormatInfo();

dateTimeFormatInfo.Calendar = new NewCalendar();

The InvalidOperationException message is "Cannot set sub-classed Globalization.NewCalendar object to System.Globalization.DateTimeFormatInfo object.".

The Explanation

The DateTimeFormatInfo.Calendar property setter block includes a "domain safety check". This check tests that the Calendar object being assigned to the Calendar property comes from the same assembly as the System.Globalization.CultureInfo class (i.e. mscorlib.dll). So if your new Calendar class does not originate from mscorlib.dll then an exception will be thrown. The problem is that only Microsoft can make changes to mscorlib.dll. Consequently there is no way that your new Calendar class can be used with DateTimeFormatInfo objects and therefore no way that you can use your own Calendar classes in custom cultures.

As an aside you might consider assigning the new Calendar object to the CultureAndRegionInfoBuilder.AvailableCalendars property:-

builder.AvailableCalendars = new Calendar[] { new NewCalendar() };

This assignment results in a NotSupportedException with the message "Custom calendars are not currently supported.". The message gives a clear indication that this feature is not yet available in the .NET Framework 2.0 but that it might become available at some future date.

Currently rated 4.5 by 2 people

  • Currently 4.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by: Guy Smith-Ferrier
Posted on: Saturday, July 15, 2006 at 1:00 AM
Categories: Internationalization
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Related posts