Search code examples
c#string-interpolationc#-6.0

Does C# 6.0's String interpolation rely on Reflection?


Short and simple. Does the new string interpolation in C# 6.0 rely on reflection? I.e. does

string myStr = $"Hi {name}, how are you?";

use reflection at runtime to find the variable "name" and its value?


Solution

  • No. It doesn't. It is completely based on compile-time evaluation.

    You can see that with this TryRoslyn example that compiles and decompiles this:

    int name = 4;
    string myStr = $"Hi {name}, how are you?";
    

    Into this:

    int num = 4;
    string.Format("Hi {0}, how are you?", num);
    

    string interpolation also supports using IFormattable as the result so (again using TryRoslyn) this:

    int name = 4;
    IFormattable myStr = $"Hi {name}, how are you?";
    

    Turns into this:

    int num = 4;
    FormattableStringFactory.Create("Hi {0}, how are you?", new object[] { num });