I suggest you ...

String interpolations in C#

Enable string interpolations in C#.

The interpolation should happen during compile time, so there are no performance penalties paid during runtime.

The Boo implemenation is a good place to start:
http://boo.codehaus.org/String+Interpolation

These should work:

var a = "Now is $(DateTime.Now)."
var b = "Tomorrow will be $(DateTime.Now.AddDays(1))"
var c = "This list has $(list.Count()) items."

744 votes
Vote
Sign in
Check!
(thinking…)
Reset
or sign in with
  • facebook
  • google
    Password icon
    I agree to the terms of service
    Signed in as (Sign out)
    You have left! (?) (thinking…)
    Giovanni BassiGiovanni Bassi shared this idea  ·   ·  Flag idea as inappropriate…  ·  Admin →

    43 comments

    Sign in
    Check!
    (thinking…)
    Reset
    or sign in with
    • facebook
    • google
      Password icon
      I agree to the terms of service
      Signed in as (Sign out)
      Submitting...
      • Thomas LevesqueThomas Levesque commented  ·   ·  Flag as inappropriate

        I agree with Dmitriy, this feature is not as good an idea as it seems.

        The first obvious problem is that it doesn't allow localization: the string has to be in the code so that the variables can be interpolated, so they can't be extracted to resource files to be localized. So unless the app only supports one language, this feature could only be used for strings that are not intended to be seen by the user (logs, paths, URIs, etc).

        A better approach, IMO, would be to improve String.Format to support named placeholders instead of numbered placeholders. I have a working implementation here:

        https://github.com/thomaslevesque/NString#stringtemplate

      • Dmitriy KrasnikovDmitriy Krasnikov commented  ·   ·  Flag as inappropriate

        -1
        I think it would be better to extend format functionality. It's more familiar for c# developers and easier to track during re factoring and string (resource) management.
        Pleas at least make Format an extension function, so I can use "A + {0} = <3".Format("Me")
        And with all the formatting options "Price is {0:C}".Format(45); for currency formatting or something.

      • Anonymous commented  ·   ·  Flag as inappropriate

        Personally I would lean towards special prefix for the string-to-be-interpolated. $"..." seems to be a good format. "...\{...}..." seems to be (1) somewhat confusing because you learn that the string is indeed an interpolated string only after scanning its contents for a while (the tail of the string may be off-screen), (2) non-symmetric (opening brace looks escaped, but closing doesn't, this may potentially create additional complications for manual parsing), (3) the escape character gets double meaning, so it's not immediately clear what "\\\n\{" should mean (first two escape characters are actually escapes, while the third one declares a substitution), so it's easy to confuse the two cases.

      • XXXOXXXO commented  ·   ·  Flag as inappropriate

        In addition, I think that although string-interpolation would already be a nice addition, it could be stronger with more features. As it is done for string generation, I think of a specific syntax for pluralization or genderization.

        var string = "There are $(list.Count()) item$(list.Count()>1?\"s\":\"\").";

        This string is a bit complicated, I'm sure we can do better and/or shorthands.

        var string = "There are $(list.Count()) item$(*s).";

        This is just a simple idea of a shorthand, * means that if the previous non-stared argument is greater than 1 then display the rest of the string, else don't.

        Just an idea... :)

      • XXXOXXXO commented  ·   ·  Flag as inappropriate

        String interpolation would be awesome but the @ of the razor syntax could be confusing when working with SQL queries with parameters (not only for developpers but also for the compiler if you have variables names and sql parameters with the same name the replacement might be done in the string and injection would become possible...).

        I personnaly like the $varName or $(expression) syntax inside the string.
        I think however that a string starter like $ for this purpose like the @ for multiline strings is unecessary and the compilation should transform the string-interpolated syntax into the best possible string construction (string.format or string.concat).

      • Jonathan GillJonathan Gill commented  ·   ·  Flag as inappropriate

        I would want something like the following.

        All these example should yield strings like "My name is Jonathan and the date is 2/27/2014" with an en-US culture.

        var example1 = string.format($"My name is {name} and the date is {date:d}", "Jonathan", DateTime.UtcNow);

        var anonObj = new { Name = "Jonathan", DateProperty = DateTime.UtcNow };
        var tradObj = new Thing(){ Name = "Jonathan", DateProperty = DateTime.UtcNow } ;
        var example2 = string.format($"My name is {name} and the date is {date:d}", anonObj.Name, tradObj.DateProperty);

        var example3 = $"My name is {name} and the date is {date:d}".Interpolate(anonObj.Name, tradObj.DateProperty);

        var example4 = $"My name is {name} and the date is {date:d}".Interpolate(anonObj);

        var example5 = $"My name is {name} and the date is {date:d}".Interpolate(anonObj, new CustomFormatProvider());

        var example6 = $"My name is {name} and the date is {date:d}. I want to include $$$$$$$ in my text".Interpolate(anonObj);

        // Note: Perhaps merge vs. interpolate would make the feature more discoverable
        var example6 = $"My name is {name} and the date is {date:d}. I want to include $$$$$$$ in my text".Merge(anonObj);

      • Richard GibsonRichard Gibson commented  ·   ·  Flag as inappropriate

        I like Mads' suggestion on syntax - it's better than what we have now!

        However, I think an even better syntax to use would be Razor.

        E.g. "The person is called @person.Name and is @person.Age years old"

        This has the advantage of being a) familiar to most devs and b) being super terse. Most of the time you don't need any kind of parentheses. If you do need something more complicated than just a variable name or property access then, as in Razor, you're covered with:

        "The two lists have @(item1.Count + item2.Count) in them"

        Perhaps, in order to not break compatibility, we could have a new way of starting strings? I'm thinking of some kind of prefix character in the same way that we use @ for strings with newlines etc. Maybe:

        var message = \"Hello @name, and welcome to my program.";

      • Giovanni BassiGiovanni Bassi commented  ·   ·  Flag as inappropriate

        I like the idea of using \.

        Still, I wouldn't limit the expressions inside the curlies. Most languages that have string interpolation allow any expression inside the curlies, and it might confusing people used to how this works for other languages. It is not what you'd expect. Can't we just adhere to what has become a common practice, and allow just any expression inside the curlies? The compiler could easily interpret the code inside the curlies as normal code and move on. Right?

      • Martijn HoekstraMartijn Hoekstra commented  ·   ·  Flag as inappropriate

        The proposed syntax by Mads Torgersen looks good enough to me; it won't be a breaking change, and tags on to the existing syntax. I'd like this.

      • Blue RajaBlue Raja commented  ·   ·  Flag as inappropriate

        Mads, what about leading the string with some character, like we already do with @"" strings?

        So your example could be eg.

        $"The price of {itemName} is {price:N2}"

      • Mads Torgersen [MSFT]Mads Torgersen [MSFT] commented  ·   ·  Flag as inappropriate

        On the C# design team we have been discussing what a string interpolation feature would look like if we were to hypothetically add it to a future version of the language.

        We are currently leaning towards a "...\{ ... } ... " syntax. The only way to add this to existing strings without breaking code is to use the escape character, "\". People are already used to {...} from String.Format, so that's familiar. Finally, if we limit the syntax of the expressions you can provide inside the curlies a bit, we could probably let you add format specifiers:

        "The price of \{itemName} is \{price:N2}"

        instead of

        String.Format("The price of {0} is {1:N2}", itemName, price)

        I am curious if anyone has thoughts on this syntax?

        Thanks,

        Mads Torgersen [MSFT]

      • Giovanni BassiGiovanni Bassi commented  ·   ·  Flag as inappropriate

        @David Boarman
        It works fine, but it is insufficient. Code readability suffers with string.format. Also, this is a really small change that Microsoft could add to make the language more elegant. Plus all the other things I have already replied on this topic before (see below).

      • David BoarmanDavid Boarman commented  ·   ·  Flag as inappropriate

        What is wrong with String.Format?

        var a = string.Format("Now is {0}", DateTime.Now);
        var b = string.Format("Tomorrow will be {0}", DateTime.Now.AddDays(1));
        var c = string.Format("This list has {0} items.", list.Count());

      • Giovanni BassiGiovanni Bassi commented  ·   ·  Flag as inappropriate

        @ThomasX
        The term is well known in the computer science world and used by many computer languages and experts: http://en.wikipedia.org/wiki/String_interpolation

        Official sites:
        CoffeeScript:
        http://coffeescript.org/#strings
        PHP:
        http://php.net/manual/en/language.types.string.php
        Ruby:
        http://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-php/

        It is not because you don't know it, that it is wrong.
        Apparently, some uninformed programmer did not study enough.

      • ThomasXThomasX commented  ·   ·  Flag as inappropriate

        Why is this called interpolation? It should be called substitution. Apparently some script kiddie is trying to impress with his half-knowledge.

      • Anonymous commented  ·   ·  Flag as inappropriate

        Old post is old, but using the Razor syntax (@) may prove more consistent with newer (at least that) part of the .NET ecosystem.

        var a = "Now is @(DateTime.Now)";
        var b = "Tommorow will be @(DateTime.Now.AddDays(1))";

      ← Previous 1 3

      Feedback and Knowledge Base