How to get the country name from the 2-letter country code (alpha-2) in VB.NET

1 Answer

0 votes
Imports System
Imports System.Globalization

Module CountryLookup

    '------------------------------------------------------------
    ' GetCountryName
    ' A small, focused function that receives a 2-letter ISO code
    ' and returns the corresponding country name.
    '
    ' Uses RegionInfo, which is part of the .NET Framework and
    ' understands ISO-3166 country codes. If the code is invalid,
    ' the function returns Nothing to signal failure.
    '------------------------------------------------------------
    Function GetCountryName(alpha2 As String) As String
        Try
            ' Normalize input: trim whitespace and convert to uppercase
            Dim normalized As String = alpha2.Trim().ToUpperInvariant()

            ' RegionInfo can be constructed from an ISO alpha-2 code
            Dim region As New RegionInfo(normalized)

            ' RegionInfo.DisplayName gives the localized country name
            Return region.DisplayName

        Catch ex As ArgumentException
            ' Thrown when the code is invalid; return Nothing to indicate no match
            Return Nothing
        End Try
    End Function

    '------------------------------------------------------------
    ' Main
    ' Demonstrates the function with a few sample codes.
    '------------------------------------------------------------
    Sub Main()
        Dim codes() As String = {"US", "GB", "FR", "ZZ"} ' ZZ is intentionally invalid

        For Each code In codes
            Dim name As String = GetCountryName(code)

            If name IsNot Nothing Then
                Console.WriteLine($"{code} → {name}")
            Else
                Console.WriteLine($"{code} → (invalid code)")
            End If
        Next
    End Sub

End Module



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

 



answered Sep 18 by avibootz
...