Li Tian Gong
Li Tian Gong

Reputation: 393

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

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.

Upvotes: 7

Views: 6300

Answers (3)

Yossi
Yossi

Reputation: 79

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();
}

Upvotes: -1

Lukasz Madon
Lukasz Madon

Reputation: 14994

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);

Upvotes: -3

David Hedlund
David Hedlund

Reputation: 129792

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.

Upvotes: 11

Related Questions