Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,239 questions

56,142 answers

573 users

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 3 days ago by avibootz
...