Reputation: 875
I would like to create a wrapper class to replace the CultureInfo base class. For example; in my code I have
var cultureInfo = new CultureInfo (stringVariableForCultureName);
I would like to replace that line for this other:
var cultureInfo = new CultureInfoWrapper (stringVariableForCultureName);
The reason is that I don't have control of the value passed to initialize the CultureInfo and I want to avoid the error exception defaulting the CultureInfo
So my CultureInfoWrapper constructor should be something like:
public CultureInfoWrapper(string cultureName)
{
try
{
return new CultureInfo(cultureName);
}
catch (Exception exception)
{
return new CultureInfo(DefaultCultureName);
}
}
Can you help me to define the wrapper class?
Upvotes: 1
Views: 94
Reputation: 460158
You could use this implementation, note that i've handled the CultureNotFoundException
:
public class CultureInfoWrapper
{
private readonly CultureInfo _cultureInfo;
public CultureInfo Value
{
get { return _cultureInfo; }
}
public CultureInfoWrapper(string cultureName, string fallbackCultureName = "en-US")
{
try
{
_cultureInfo = new CultureInfo(cultureName);
}
catch (CultureNotFoundException)
{
_cultureInfo = new CultureInfo(fallbackCultureName);
}
}
}
Another approach would be to load all cultures once, then you can use this optimized version:
public class CultureInfoFinder
{
private static readonly CultureInfo DefaultCulture = new CultureInfo("en-US");
private static Dictionary<string, CultureInfo> _allSpecificCultures;
static CultureInfoFinder()
{
_allSpecificCultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures)
.ToDictionary(c => c.ToString(), c => c, StringComparer.InvariantCultureIgnoreCase);
}
public static CultureInfo Get(string cultureName)
{
CultureInfo c;
bool knownCulture = _allSpecificCultures.TryGetValue(cultureName, out c);
return knownCulture ? c : DefaultCulture;
}
}
For example:
CultureInfo deDE = CultureInfoFinder.Get("de-DE");
Upvotes: 5