C# Error in calendar after upgrading project .net target framework from 3.5 to 4.5

179 Views Asked by At

I have the below function of buildculture for calendar:

private void buildCulture(string culture, string calendarType)
{

    CultureInfo ci=null;
    try
    {
        if (string.IsNullOrEmpty(culture))
        {
            ci = System.Threading.Thread.CurrentThread.CurrentCulture;
        }
        else
        {
            try
            {
                ci = new CultureInfo(culture);
            }
            catch (System.ArgumentException)
            {
                ci = System.Threading.Thread.CurrentThread.CurrentCulture;
            }
        }

        // Calendar is from system.windows.control.calendar, 
        // ci is from system.globalization.calendar:
        Calendar originalCal = ci.Calendar;

        if (!string.IsNullOrEmpty(culture) || 
             originalCal.ToString().Replace("System.Globalization.", "") != culture)
        {
            foreach (Calendar supportCal in ci.OptionalCalendars)
            {
                if (calendarType == 
                      supportCal.ToString().Replace("System.Globalization.", ""))
                {
                    ci.DateTimeFormat.Calendar = supportCal;
                }
            }
        }
    }
}

This function still work in .net version 3.5. But after I upgrade to .net 4.5, there's an error appear for line Calendar originalCal = ci.Calendar which says: Calendar is an ambiguous reference between system.windows.control.calendar and system globalization.calendar.

How do we fix this guys?

2

There are 2 best solutions below

2
On

You would want to use the either the fully qualified name when declaring the object, like so:

System.Globalization.Calendar originalCal = ci.Calendar;

Or, if you know you aren't using the System.Windows.Control.Calendar type, you can alias the type Calendar to the one in System.Globalization with the following using:

using Calendar = System.Globalization.Calendar;
0
On

If I understand you correctly, system.globalization.calendar is probably what you want to use, since you seem to be working with the format of dates.

system.windows.control.calendar does not contain calendar data, but rather a calendar control - the graphics rendered as a calendar that is.

To achieve this, either remove any import statement that references system.windows.control.calendar.

If that is not possible (if you're using something else under System.windows.control, so Calendar gets included implicitly), then declare an alias for the system.globalization namespace:

using glob = System.Globalization;

This defines glob as short for the namespace System.Globalization, and this will allow you to refer to the correct Calendar class as follows:

var ci = new glob.CultureInfo(culture);
glob.Calendar myCal = ci.Calendar;

PS: You could shorten it even more if you wanted to, but personally, I think anything shorter than glob will make it's meaning less clear.