CultureInfo.InvariantCulture in .ToString() - c#

I am currently fixing FxCop issues so I encountered issue where I have to provide cultureinfo when converting a string using ToString() .
Currently in my code nothing we are passing as IFormatProvider so I have read some msdn articles saying that when you don't pass any value for cultureinfo it will assign a default value and when you specify CultureInfo as InvariantCulture it will be independent of any culture.
My question is, "Are default and CultureInfo.InvariantCulture one and the same? Can I replace all my code from default to InvariantCulture?"
Ex :
int st = 123;
String s = st.ToString(123); // this will be taken as default
String s = st.ToString(123, CultureInfo.InvariantCulture); // culture is specified externally
Are the second and third lines equivalent?

Is default and CultureInfo.InvariantCulture are one and the same?
No, absolutely not. The default culture depends (initially) on the operating system settings. The invariant culture is meant to be a "neutral" culture.
Your example of 123 isn't a great one, because most (all?) cultures will represent integers the same way - at least until you get into formats with grouping separators etc. (I don't think .NET supports non-Arabic numerals when formatting integers.)
Compare that with formatting a decimal value, for example:
decimal x = 123.45m;
Console.WriteLine(x.ToString()); // Might be 123,45
Console.WriteLine(x.ToString(CultureInfo.InvariantCulture)); // Always 123.45
If you run the above code in (say) France, the default culture will be French, which uses a comma as a decimal separator - so it will print out "123,45".
The rule of thumb to remember is that the invariant culture is suitable for machine-to-machine communications (e.g. formatting values in JSON or XML) whereas other cultures are more suitable for displaying information directly to users.
Although the default culture is originally based on the operating system settings, it can be changed using Thread.CurrentCulture and Thread.CurrentUICulture; the latter is used for looking up translated resources, whereas the former is used for formatting decisions like the above. You can set these properties on any thread, but typically you'd use Thread.CurrentThread.CurrentCulture = ...

No, they are not the same.
The first will take the regional settings from the computer or the culture settings from the application thread running.
The second one will take the English language, according to MSDN:
The invariant culture is culture-insensitive; it is associated with the English language but not with any country/region.

Related

Culture-insensitive VS Culture-sensitive

I've seen a lot of time about Culture-insensitive and Culture-sensitive i don't Knew exactly what are The difference between them.
In some books they divide the Specifiers into Two categories:
Culture-insensitive date/time format strings and
Culture-sensitive date/time format strings
I knew the specifiers but I have no idea abut sensitive and insensitive.
could anyone guide me in this?
To start, I would refer you to .NET Globalization & Localization for more information.
There are certain values/entities that get treated differently in different countries and regions. Such entities include currency symbol, digit separators, dates and more. When displaying this data to your user, you have to format it in a way that makes sense to them. If for instance you display money in a loan amortization application as follows:
Console.WritLine("$" + amount.ToString());
this will only work well in countries that use dollars. And there's no other formatting. To make this culture sensitive, you will have to do it this way...
Console.WriteLine(amount.ToString("C"));
By doing it that way, .NET will use the correct currency symbol, digit separator and decimal point for the culture the application is run in.
There are cases in which you will need to show such data in a specific culture. Doing it this way will change the way it is displayed, you can however provide the culture to use in the following way...
static void Main(string[] args)
{
decimal foo = 23434534.53M;
Dump(foo);
var culture = CultureInfo.CreateSpecificCulture("en");
CultureInfo.CurrentCulture = culture;
Dump(foo);
culture = CultureInfo.CreateSpecificCulture("es");
CultureInfo.CurrentCulture = culture;
Dump(foo);
culture = CultureInfo.CreateSpecificCulture("en-ZA"); // South Africa
CultureInfo.CurrentCulture = culture;
Dump(foo);
}
static void Dump(decimal value)
{
Console.WriteLine(value.ToString("C"));
Console.WriteLine(DateTime.Now.ToLongDateString());
}
When you change the culture at run time, subsequent calls to display the value as money will change the currency symbol, the location of said currency symbol in some cases, the digit separators and the decimal point.
This also affects how dats are displayed as you can see.
You can also use this to change the text displayed in your UI. If you have an app that supports multiple languages, for instance US English, British English, Spanish and French you are not required to know these languages beforehand. Also, you can no longer hard code you string literals like "First name:". Some simple things may differ like the spelling of color (UK English colour). Such things might be inconsequential to someone who doesn't speak English but are taken seriously in the respective countries. If your app is showing children the correct spellings for instance, you want it to get it right for the place it is in.
In this case you can set a UI culture and use resource (resx) files to place your strings in. At runtime you load your strings from the resource files and the .NET runtime can load the correct resx file based on the culture it detects the PC is set to. If there is no match, it will fall back to your default culture.
In my test app I created 2 resource files, one called Strings.resx and the other Strings.es.resx. The first will be the default language, and the other is for Spanish. When greeting a user, I won't have to hard code the greeting but can use it as follows
static void Main(string[] args)
{
Console.WriteLine(ConsoleApp1.Strings.HelloString);
CultureInfo.CurrentUICulture = CultureInfo.CreateSpecificCulture("es");
Console.WriteLine(ConsoleApp1.Strings.HelloString);
}
resulting in the following
Together these techniques can help you create an application that is sensitive to the language and culture of the user. If you need to override that, you can also do that knowingly by specifying which culture to use when presenting your data. Hard coding the entities that vary is not culture sensitive and will display the same regardless of the locale of the machine it is run on.
Culture-sensitive operations should be used when interacting directly with users. Culture-insensitive operations should always be used when interacting with back-end processes and interchange systems, including persisting data. The data that backs culture specific operations can change for many reasons. The data that backs culture-insensitive operations never changes and so is safe to persist and interchange.

C# Check if string is in a value format

I'm wondering if there's simple way to check if a string is in a value format of any kind. Meaning the number one-thousand could be represented in any of the following ways:
1000
1000.00
1,000
1,000.00
$1,000.00
I've tried double.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out n) but that isn't working for items with the currency symbol out in front. So I tried double.TryParse(value NumberStyles.Any | NumberStyles.AllowCurrencySymbol, CultureInfo.InvariantCulture, out n) but that is also not working.
Basically I'd like to check if a value can be considered a number value at all.
The invariant culture does not use $ as its currency symbol; it uses ¤.
Picking the correct culture for parsing is tricky. Obviously, it is best to use the same culture that was used to format the value to begin with. If you know which culture was used, you’re lucky :).
By default, unless a specific culture is specified, CurrentCulture will be used. The current culture can be overridden and set on a per-thread basis, but it defaults to the locale settings of the host operating system. In the absence of other information, CurrentCulture is a reasonable first guess.
I would suggest you || together at least two TryParse calls: one for CurrentCulture (or your best guess as to the culture of origin), and a fallback using InvariantCulture. Include AllowCurrencySymbol on both.
You can use regular expressions
https://regexone.com/references/csharp
you can use below code to accept your cases
1000
1000.00
1,000
1,000.00
$1,000.00
string pattern = #"^\$?(\d{1,3}(\,\d{3})*(\.0{2})?)|(\d+(\.0{2})?)$";
Match result = Regex.Match("$100,000.00", pattern);
if (result.Success)
// your input is in format

CultureInfo.InvariantCulture in plain english

I know that culture rules for dates/numbers is enough for an entire book, I think I have a simple question though..
Does using InvariantCulture basically mean that you explicitly define what culture the value (date/number/whatever) will be inputted/displayed as? And it overrides any other culture setting (such as the user agent's setting)?
If an app is built for an audience of one and only one culture, would it make sense to use InvariantCulture and define how you want values inputted/displayed each time?
Does using InvariantCulture basically mean that you explicitly define what culture the value (date/number/whatever) will be inputted/displayed as?
No. It's just a culture which is a bit like US English, except for a few things like currency sign. It's usually used to format/consume text which is to be understood or was produced by another computer rather than a human.
If an app is built for an audience of one and only one culture, would it make sense to use InvariantCulture and define how you want values inputted/displayed each time?
No, you would use the relevant CultureInfo for that culture. You could also explicitly define the format for dates etc, but that's an orthogonal concern. It may well be best to use one of the predefined standard formats for that culture, but if none of those meet your needs you can always be explicit.
InvariantCulture is Independent of any culture or any factor.
For example if you're using new CultureInfo("en-US") it will get you US English Culture(Which may not be actual US English Culture because OS gives you option to change these setting in Control Panel) it will return the modified version of Culture of "en-US" if any custom formatting applied to it.
In other words InvariantCulture will always gives you a Culture which can never be changed across Systems.
Let's assume you want to serialize some value(say double) and pass to another application or some other thread which is running in different culture leads to serious problems.
Consider the following code
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr");
double source = 455.62d;
string serialized = source.ToString();//455,62 since `, is the decimal seperator` in "fr"
Thread t = new Thread((x) =>
{
double deserialized = double.Parse(((string)x));
Console.WriteLine(string.Format("Deserialized value is {0}", deserialized));//outputs 45562
});
t.CurrentCulture = new CultureInfo("en-US");
t.Start(serialized);
numbers matters more right? consider this string denotes AccountBalance?
Hope this helps
With specific regard to DateTime, the best advice I can give is to use CultureInfo.InvariantCulture for ParseExact and ToString when you have an exact format in mind. (You can also use it with Parse if you happen to know that your input format matches the invariant culture's formats, but I typically avoid this.)
Don't use the invariant culture when interacting with a user.
Keep in mind that the culture contains several items, including the ordering of day/month/year parts, the date and time part separator characters, the character encoding, and the language-specific names of the days of the week, months of the year, and abbreviations including am/pm.
Some examples of when you should use the invariant culture:
Files on disk, especially text files of a predefined format
External APIs, especially JSON or XML
Unit tests, unless you are specifically testing culture issues
Some examples of when you should use a specific culture such as en-US:
User Interface
Reports

Formatting Currency to ALWAYS use USD regardless of users culture

This should be simple but I cannot find the answer anywhere.
On our asp.net MVC site, we show currency values and I need these currency values to Always be in USD regardless of the users culture settings.
If I use string.format("{0:C}",value) then it shows the value in what ever culture the use has set.
This is incorrect for us as $1000.00 is not the same thing as 1000.00 euro
I still need to use the language side of this, meaning if they are in France I want to use the French localization resource, so I don't want to completely disregard their culture settings, but how can I make sure the currency is always shown in USD?
Explicitly pass culture to the Format call:
string.Format(new CultureInfo("en-US"), "{0:C}",value)
If you have to mix it with other languages - save result of formatting currency value and insert into other places as string.
Side note: using "en-US" (or any other hard-coded culture) will lead to potentially mismatched representation of negative values i.e. some cultures use -100, while other (100) for negative amounts.
You would have to specify CurrentCulture to be en-US and leave CurrentUICulture as is.
I usually do this in global.asax.cs in the Application_BeginRequest event
System.Threading.Thread.CurrentThread.CurrentCulture =
new System.Globalization.CultureInfo("en-US", false);
It is possible to specify the culture in web.config file but that has one drawback - it takes into account the customized regional settings of the server (if the administrator changed the currency or date format on the server for the en-US culture, it would get picked up this way) - so you can't ever be sure that the application will behave exactly the same as when you created/tested it.

creating custom CultureInfo for country, language combination

I am working on a .net 4.5 application that needs to be mult lingual supporting multi cultures etc.
The following is sample list of Countries/Languages
Russia / Russian
Belgium / French
Belgium / Dutch
For all the above, there is a CultureInfo object that can be created based upon the above culture names
ru-RU
fr-BE
nl-BE
When the user enters the site, I set Thread.CurrentThread.CurrentCulture and Thread.CurrentThread.CurrentUICulture to the culture created with the above names eg.
Thread.CurrentThread.CurrentCulture = new CultureInfo("nl-BE", false)
Thread.CurrentThread.CurrentUICulture = new CultureInfo("nl-BE", false)
All the above names are valid culture names.
No however I need to added another culture name, language of English in Russia. But the problem is the code en-RU is not valid so when I create new CultureInfo("en-RU", false) I get a CultureNotFoundException as en-RU is not valid.
With this culture, I want the formatting etc of Russia around numbers, dates etc, but I want the language on the site to be English. Is it possbile to create custom CultureInfo objects for invalid culture names with the behaviour of the country (Russia)?
Is it possbile to create custom CultureInfo objects for invalid culture name
Yes.
Make use of CultureAndRegionInfoBuilder to help create the custom CultureInfo. (NB. once you have code to create a culture, the settings to do this can be saved to XML and then loaded, eg. from a resource, which should need less code at runtime.)
An example project how to do that, plus downloadable code, can be found at CodeProject. An important note from the article is that, even though this class sits in the System.Globalization namespace, it is not available by default, quote:
We’ll start by referencing the assembly sysglobl.dll and add a using statement for the namespace System.Globalization.
You may have to mix and mix and match - have a culture object for English which you use for English text but a culture object of ru-Ru (Russian) for numeric formatting.
Or even better create a custom culture combining the two
Create custom culture in ASP.NET
You should use CultureInfo.InvariantCulture Property
The invariant culture is culture-insensitive; it is associated with
the English language but not with any country/region. You specify the
invariant culture by name by using an empty string ("") in the call to
a CultureInfo instantiation method. CultureInfo.InvariantCulture also
retrieves an instance of the invariant culture. It can be used in
almost any method in the System.Globalization namespace that requires
a culture. The objects returned by properties such as CompareInfo,
DateTimeFormat, and NumberFormat also reflect the string comparison
and formatting conventions of the invariant culture.
CultureInfo.InvariantCulture Property
This is other option Custom Global Application Culture

Categories