How to get the country name from the 2-letter country code (alpha-2) in C#

1 Answer

0 votes
using System;
using System.Globalization;

class CountryLookup
{
    // ------------------------------------------------------------
    // GetCountryName
    // Receives a 2‑letter ISO country code (alpha‑2) and returns
    // the corresponding country name.
    //
    // RegionInfo understands ISO‑3166 codes and exposes the
    // localized country name via DisplayName.
    //
    // If the code is invalid, the method returns null to signal
    // that no country could be resolved.
    // ------------------------------------------------------------
    static string GetCountryName(string alpha2)
    {
        try
        {
            // Normalize input: trim whitespace and convert to uppercase
            string normalized = alpha2.Trim().ToUpperInvariant();

            // RegionInfo can be constructed directly from an ISO alpha‑2 code
            var region = new RegionInfo(normalized);

            // DisplayName provides the human‑friendly country name
            return region.DisplayName;
        }
        catch (ArgumentException)
        {
            // Thrown when the code is invalid; return null to indicate failure
            return null;
        }
    }

    // ------------------------------------------------------------
    // Main
    // Demonstrates the lookup function with several sample codes.
    // ------------------------------------------------------------
    static void Main()
    {
        string[] codes = { "US", "GB", "FR", "ZZ" }; // ZZ is intentionally invalid

        foreach (var code in codes)
        {
            string name = GetCountryName(code);

            if (name != null) {
                Console.WriteLine($"{code} → {name}");
            }
            else {
                Console.WriteLine($"{code} → (invalid code)");
            }
        }
    }
}



/*
run:

US → United States
GB → United Kingdom
FR → France
ZZ → (invalid code)

*/

 



answered Sep 18 by avibootz
...