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?
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;
}
}
}