Does .net have an inbuilt way of validating region names before creating a RegionInfo object?

230 views Asked by At

My code looks like this:

var twoLetterCountryCode = *Get possibly invalid value from database*;
if (!string.IsNullOrEmpty(twoLetterCountryCode) && twoLetterCountryCode.Length == 2)
{
    try
    {
        var region = new RegionInfo(twoLetterCountryCode);
    }
    catch (ArgumentException ex)
    {
        *log exception*
    }
}

Is there an inbuilt way of validating the region name so I don't have to use try/catch?

1

There are 1 answers

0
Tim Schmelter On BEST ANSWER

No, there is no RegionInfo.TryParse, I don't know why they didn't provide it. They have the information but everything is internal, so you can't access it.

So in my opinion the try-catch is fine. You could put it in an extension method.

public static class StringExtensions
{
    public static bool TryParseRegionInfo(this string input, out RegionInfo regionInfo)
    {
        regionInfo = null;
        if(string.IsNullOrEmpty(input))
            return false;
        try
        {
            regionInfo = new RegionInfo(input);
            return true;
        }
        catch (ArgumentException)
        {
            return false;
        }
    }
}