Deriving ISO Country Codes within the .NET Framework / C#

 

 

World Flags

I recently worked on a project for an international banking organisation in Umbraco. It came to light that when deriving a list of countries from the .NET Framework, many were not displaying all the countries available in the ISO 3666 list – which form the codes for representation of names of countries and their subdivisions.


In this case the situation was instantly highlighted by the absence of Mauritius, the good people of Mauritius would not be happy - and rightly so.


Whilst investigating the issue I came across the solution as a simple nuget package - maybe this article will at first chime with the way you are currently deriving a country list and then provide a quick answer to getting the full list from the nuget package.


The native method below generates a dictionary of 142 countries, the nuget package sourced method is currently returning 249 countries; the nuget package is updated against the ISO 3666 list regularly - reflecting our ever-changing world.

 

Native C# Method found in many posts online.

 

Along the lines of ...


public static Dictionary<string,string> CountryList() { //Create a Dictionary Dictionary<string, string> countryDictionary = new Dictionary<string, string>(); //Get specific CultureInfo CultureInfo[] getCultureInfo = CultureInfo.GetCultures(CultureTypes.SpecificCultures); foreach (CultureInfo getCulture in getCultureInfo) { RegionInfo getRegionInfo = new RegionInfo(getCulture.LCID); //add each country into the Dictionary of code/name - no duplicate keys if (!(countryDictionary.ContainsKey(getRegionInfo.Name))) { countryDictionary.Add(getRegionInfo.Name, getRegionInfo.EnglishName); } } //return country dictionary return countryDictionary; }

Nuget Package C# Method.

The nuget package in question is here: https://www.nuget.org/packages/ISO3166/

 

Then simply ...

    var countries = ISO3166.Country.List;

Or perhaps you want a a dictionary ...

    var countryDictionary = ISO3166.Country.List.OrderBy(x=>x.Name).ToDictionary(x => x.TwoLetterCode, x => x.Name);

 

If you or your internal team need any consultation or support with .NET development or Umbraco CMS you can find out more here or call us on 0113 320 1302