Difference between CultureInfo.Get and new CultureInfo

 
 
  • Gérald Barré

When you want to get a CultureInfo object, you can use the static method CultureInfo.GetCultureInfo or the constructor of the CultureInfo class. In this post, I describe the difference between CultureInfo.GetCultureInfo and the constructor of the CultureInfo class.

C#
var cultureInfo1 = CultureInfo.GetCultureInfo("en-US");
var cultureInfo2 = new CultureInfo("en-US");

The constructor creates a new instance from the specified culture. You can edit the data from this instance. This means you can change the calendar, the number format, and so on. The following code shows how to change the currency symbol:

C#
var culture = new CultureInfo("en-US");
culture.NumberFormat.CurrencySymbol = "€";

Console.WriteLine(42.ToString("C", culture)); // €42.00

The static method CultureInfo.GetCultureInfo returns a read-only instance of the specified culture. You can't edit the data from this instance. As you can't edit the culture, the method can cache the instance. So, it can be faster and reduce memory usage.

C#
var culture1 = CultureInfo.GetCultureInfo("en-US");
var culture2 = CultureInfo.GetCultureInfo("en-US");
Console.WriteLine(ReferenceEquals(culture1, culture2)); // True

If you run a simple benchmark, you can see the allocation difference between the 2 methods (see BenchmarkDotNet) and see how the caching can help reduce memory usage.

C#
[MemoryDiagnoser]
public class CultureInfoBenchmark
{
    [Benchmark(Baseline = true)]
    public void Ctor()
    {
        _ = new CultureInfo("en-US");
    }

    [Benchmark]
    public void StaticMethod()
    {
        _ = CultureInfo.GetCultureInfo("en-US");
    }
}
MethodMeanAllocated
Ctor33.74 ns144 B
StaticMethod24.44 ns32 B

In conclusion, you should use CultureInfo.GetCultureInfo most of the time as it's very uncommon to edit a CultureInfo object.

#Additional resources

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub