Is there a way to "try parse" a string to System.Globalization.CultureInfo
Asked Answered
F

3

7

In C#, I am using

CultureInfo.GetCultureInfo(myCulture)

but the string variable may not come in a good format, is there a way to try parse the string first or verify it first.

Ferritin answered 10/9, 2012 at 5:6 Comment(3)
tryParse what ? to intBratwurst
@Bratwurst As he writes in the title, he wants to parse a string into a CultureInfo.Delete
@UweKeim, now seeing the answer the question becomes more clearer.Bratwurst
B
11

The following yields a collection of all cultures:

CultureInfo.GetCultures(CultureTypes.AllCultures)

From there, rather than GetCultureInfo you could do:

.FirstOrDefault(c => c.Name == myCulture)

Rather than AllCultures you may want to filter out SpecificCultures.

Bentlee answered 10/9, 2012 at 5:10 Comment(1)
You can even pick up all cultures in a Dictionary<,> if this is something you do all the time. As in: static readonly Dictionary<string, CultureInfo> CultureDict = CultureInfo.GetCultures(CultureTypes.AllCultures).ToDictionary(c => c.Name);Derwent
R
-1

there is no tryparse with culture objects. one way is to go through all cultures as suggested and look for one and the other way is to use the simple try parse:

try
{
    // making sure the lang is a calture
    System.Globalization.CultureInfo c = new System.Globalization.CultureInfo(lang);
}
catch
{
    lang = Session["lang"].ToString();
}
Rafael answered 26/1, 2015 at 9:45 Comment(1)
You should never ever do some thing like this! change catch to catch(CultureNotFoundException ex).Labourer
K
-3

I always use a little helper in my project. All arithmetic types got TryParse method

public static bool TryParseDouble(this string text, out double value)
{
   return double.TryParse(text, NumberStyles.Any,
                          CultureInfo.InvariantCulture, out value);
}

The usage

double value;
bool isStringOK = theString.TryParseDouble(out value);
Khamsin answered 10/9, 2012 at 5:13 Comment(1)
So what does double have to do with CultureInfo as the original poster asks?Delete

© 2022 - 2024 — McMap. All rights reserved.