What is the default culture for C# 6 string interpolation?

前端 未结 1 625
情话喂你
情话喂你 2021-01-01 09:11

In C# 6 what is the default culture for the new string interpolation?

I\'ve seen conflicting reports of both Invariant and Current Culture.

I would like a de

相关标签:
1条回答
  • 2021-01-01 09:22

    Using string interpolation in C# is compiled into a simple call to String.Format. You can see with TryRolsyn that this:

    public void M()
    {
        string name = "bar";
        string result = $"{name}";
    }
    

    Is compiled into this:

    public void M()
    {
        string arg = "bar";
        string text = string.Format("{0}", arg);
    }
    

    It's clear that this doesn't use an overload that accepts a format provider, hence it uses the current culture.

    You can however compile the interpolation into FormattbleString instead which keeps the format and arguments separate and pass a specific culture when generating the final string:

    FormattableString formattableString = $"{name}";
    string result = formattableString.ToString(CultureInfo.InvariantCulture);
    

    Now since (as you prefer) it's very common to use InvariantCulture specifically there's a shorthand for that:

    string result = FormattableString.Invariant($"{name}");
    
    0 讨论(0)
提交回复
热议问题