I need a way to detect if the Thread.CurrentThread.CurrentCulture
uses a specific language.
In particular, I need to detect if the CurrentCulture
CultureInfo
object supports/uses/is "English", regardless of the country/region -- but, there is a possibility I would want to check for other languages, also.
I know that any English language CultureInfo
objects' Name
s will be prefixed with en-
and then the region (US
, GB
etc.) - according to MSDN's Table of Language Culture Name and Codes.
So I could simply check if the current culture name "starts with" the en-
prefix:
var currentCultureName = Thread.CurrentThread.CurrentCulture.Name;
if (currentCultureName.StartsWith("en-"))
{
// We have an English language culture
}
EDIT: Similarly (as Evk pointed out) - if I were to use the TwoLetterISOLanguageName
, I could end up with the same result:
var twoLetterISOLanguageName =
Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;
if (twoLetterISOLanguageName.Equals("en", StringComparison.InvariantCultureIgnoreCase))
{
// We have an English language culture
}
Is there an alternative, or more type-safe way of checking for this, with the possibililty of needing to detect other languages (e.g. French, German etc.)? - in order to save having to write a potentially large switch
statement?
Or, is what I'm using above - and using a switch
statement the best approach?
Thanks in advance for your help and suggestions :)
There is no really a very elegant solution, what you have suggested is not bad for a few languages. You could use CultureInfo.Parent Property which will return the neutral culture.
There are some complications when there is a hierarchy where multiple parent languages available (eg: some Traditional Chinese , Taiwan). But this should be fine for DE, FR and EN.
var neutralCulture = Thread.CurrentThread.CurrentCulture.Parent.Name;
if (neutralCulture.Equals("en", StringComparison.OrdinalIgnoreCase))
{
// We have an English language culture
}
else if (neutralCulture.Equals("fr", StringComparison.OrdinalIgnoreCase))
{
// We have a French language culture
}
else if (neutralCulture.Equals("de", StringComparison.OrdinalIgnoreCase))
{
// We have a German language culture
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With