1

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?

Andrey Bushman
  • 11,712
  • 17
  • 87
  • 182
  • 2
    Is there anything wrong with this code? If the framework provided such a method it would still have to try/catch. If you are concerned about the succinctness of the code then you could create an Extension method on the string type. – James Lucas Apr 27 '15 at 07:35
  • No, I am not concerned about the succinctness of the code. But it very much influences on productivity when many incorrect values are processing in a cycle. Here I showed some results about comparring `try\catch` variant and the `TryGetObjectId` (it is a some analogy of `TryParse`): https://sites.google.com/site/bushmansnetlaboratory/sendbox/stati/database/compare 00:05:30,4050567 and 00:00:00,7027717. Big difference in productivity. – Andrey Bushman Apr 27 '15 at 07:47

1 Answers1

3

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))
{
    ...
}
Andrei Tătar
  • 7,872
  • 19
  • 37