Skip to content

Netizine/Netizine.Enums.Country

Repository files navigation

Netizine.Enums.Country

A country enum created to simplify mapping countries to a enum. It is created from the country data extracted from Wikipedia.

Using Netizine.Enums.Country

To use the country enum in your project, add the Netizine.Enums.Country NuGet package to your project.

Provides a few extension methods to quickly access country name, description, state name, ISO 3166-1 codes such as the Alpha-2, Alpha-3 and Numeric codes etc. as shown below. Extension Methods

As a example, calling the following code

var imageUri = countries.First().GetDataURIImage();

Would return data:image/png;base64,iVBO........ which you can use to render a png country flag for the United States of America United States of America

In the case of converting to and from JSON, It includes a CountryConverter that you can use to try multiple different ways to cast to the correct enum namely country name, country description, the ISO 3166-1 codes etc.

        static void Main(string[] args)
        {
            var countries = ((Country[]) Enum.GetValues(typeof(Country)))
                .Where(countryEnum => countryEnum == Country.UnitedStatesOfAmerica || countryEnum == Country.UnitedKingdom).ToList();
            var json = JsonConvert.SerializeObject(countries, Converter.Settings);
            var newCountries = JsonConvert.DeserializeObject<List<Country>>(json, Converter.Settings);
            
            //Validate USA post code
            var usa = Country.UnitedStatesOfAmerica;
            var r = new Regex(usa.GetPostalCodeRegex());
            var postalCodeValid = r.IsMatch("85001");
            var postalCodeInvalid = r.IsMatch("85001A");
        }

        public static class Converter
        {
            public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
            {
                MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
                DateParseHandling = DateParseHandling.None,
                Converters =
                {
                    CountryConverter.Singleton,
                    new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
                },
            };
        }

About

A enum helper for countries

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages