Some types has the TryParse
method, for example it is Int32
, Int64
, Boolean
, etc. It allows check the string value without try\catch block. It very much influences on productivity when many incorrect values are processing in a cycle. I need to do the same for string value of the LCID. But the CultureInfo
class has not the TryParse
method.
CultureInfo culture = null;
try {
culture = CultureInfo.GetCultureInfo(Convert.ToInt32(lcid, 16));
}
catch {
}
How can I rewrite this code?
You could cache all the CultureInfo objects by LCID in a dictionary:
var culturesByLcid = CultureInfo
.GetCultures(CultureTypes.AllCultures)
.ToDictionary(c => c.LCID, c => c);
and use TryGetValue like:
CultureInfo found;
if (culturesByLcid.TryGetValue(lcid, out found))
{
...
}