Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Language Envy - String Interpolation
Language Envy: This post is part of a series where I wish C# had a particular feature I came to like when working with other programming languages.

Every time I have to produce a string in C# the little groaning chimp that lives inside my head pulls his hair out. It's about time we had a better way of doing this.

We all use string.Format to make these string concatenations more readable, but it's still too easy to get the order wrong or miss one of the argument values and get an exception. JetBrain's Resharper can be helpful here, giving hints when you have too many or too few arguments in a call to string.Format.

So what am I whining about?

When you need to create a string that mixes literals with variables in PHP (or Ruby, or Boo, or Perl, etc) it's so much easier to type, read and maintain than in C#:

<?php
	$price = 12.34;
	$product = "DVD Media";
	echo "$product costs $price";
	//ouputs: DVD Media costs 12.34
?>

Although this would be enough to get a lot done, the interpolation syntax can help with more complicated expressions beyond simple variables:

<?php
	$order = $user->getLastOrder();
	echo "The first item in the order was {$order->item[0]}.";
	//ouputs: The first item in the order was DVD Media.
?>

One interesting thing to note is that this is a syntax for combining expression values and literals. The interpolation isn't evaluated in strings that already exist and are passed in (like some user input.) In other words, the interpolation happens at parsing time, where the string is declared. The parser will not look into an existing string and replace tokens that look like variables — at least not without you explicitly asking it to do so.

In PHP the interpolation goes a little further. Just for the sake of curiosity, check this out.

<?php
	$var1 = 1000;
	$name = 'var1';
	//recursive interpolation:
	echo "The value of the variable named $name is {${$name}}";
	//outputs: This is the value of the var named var1 is 1000 
?>

Wouldn't it be nice to have such syntax in C#? The string would probably need to be taken care of at compile time, so a statement like this:

//DOESN'T WORK YET. JUST A DAYDREAM
var text = "The price of a ${product.Name} is ${product.Price}.";

At compile time would be treated as if it had been written as follows.

var text = "The price of a " + product.Name + 
           " is " + product.Price + ".";
// OR ...
var text = string.Concat("The price of a ", product.Name, 
           " is ", product.Price, ".");

Done like the example above this would be a backwards compatibility problem. I'm sure it's possible to put some symbol before the opening double quote to make this compatible.


Posted 01-17-2009 7:50 PM by sergiopereira
Filed under: , ,

[Advertisement]

Comments

George mauer wrote re: Language Envy - String Interpolation
on 01-17-2009 9:39 PM

stackoverflow.com/.../-net-is-there-a-string-format-form-for-inserting-the-value-of-an-object-property

Not exactly this but not too bad.

You can do String.Format("My Name Is {0:Name}, and I'm placing order {1:OrderId}", user, order);

Matt Gilbert wrote re: Language Envy - String Interpolation
on 01-17-2009 10:37 PM

This is one of those little language features that can go a long way.  After spending some time with Boo, going back to string.format in C# and VB.NET really sucks.

I use VB.NET at work and so I can't help but think that something like "Option Interpolate On" would be quite possible as a backwards compatibility workaround.  Why we get XML literals instead of string interpolation is something that baffles me.

Simon Gillbee wrote re: Language Envy - String Interpolation
on 01-17-2009 10:53 PM

It's funny that you're talking about this. Phil Haack with MS posted a block entry about this and several ways of accomplishing something similar (along with performance benchmarks).

See haacked.com/.../named-formats-redux.aspx

Xerxes wrote re: Language Envy - String Interpolation
on 01-17-2009 11:17 PM

In theory, this technique is useful and helps the readability of code, but the thing i dislike the most would be the lack of type safety when defining the string. The same reason why string literals are a PITA in code in the first place - not refactor friendly.

brad wrote re: Language Envy - String Interpolation
on 01-18-2009 1:11 AM

stop being lazy.  that sort of string stuff is just a crutch.  Same with var.  i really wish people would stop being so lazy they fugly up code (esp tutorials) w/ the retarded var keyword.

sergiopereira wrote re: Language Envy - String Interpolation
on 01-18-2009 1:13 AM

@Xerxes, my suggestion was that those strings were parsed at compile time so your type safety is there. With a little more work Visual Studio could even give you IntelliSense within the strings.

sergiopereira wrote re: Language Envy - String Interpolation
on 01-18-2009 1:17 AM

@Simon, I've been following Haack's and Hanselman's posts about that for a while. I think the number of people that have posted about this type of supercharged Format method is a good indication that string interpolation would be a welcome addition to the language.

sergiopereira wrote re: Language Envy - String Interpolation
on 01-18-2009 1:26 AM

@brad, I hate to admit, but you're right. Let's all get back to assembly or straight binary code. Bunch of lazy-o's we are. Why try to improve something that works? Excuse me, I need to chop some wood for my heater then feed my horses. I'm canceling my Internet and going back to Morse code tomorrow. (I know you were just ranting... I'm just joking)

RhysC wrote re: Language Envy - String Interpolation
on 01-18-2009 2:47 AM

I can see where brad is coming from, and oce shared his view point. Incremental improvements accross the board are something we shold be encouraging. var for example is a good thing, I originally did not like/understand it, but it sure makes refatoring easier and improves the code readability.

Scott Seely wrote re: Language Envy - String Interpolation
on 01-18-2009 10:07 AM

FWIW, we recently added this feature to OpenSocial (www.opensocial.org) in our markup language. We modeled the feature after JSPEL (Java Server Pages Expression Language). Doing something similar in ASP.NET via Eval works and is a close substitute.

George mauer wrote re: Language Envy - String Interpolation
on 01-18-2009 8:39 PM

There is a whole lot to be said for decreasing noise and improving readability, it is not just laziness.

Plus var is very helpful for for loops or using blocks when you might change the enumerated type as part of a refactoring.  

Dew Drop - January 18, 2009 | Alvin Ashcraft's Morning Dew wrote Dew Drop - January 18, 2009 | Alvin Ashcraft's Morning Dew
on 01-18-2009 9:14 PM

Pingback from  Dew Drop - January 18, 2009 | Alvin Ashcraft's Morning Dew

Reflective Perspective - Chris Alcock » The Morning Brew #267 wrote Reflective Perspective - Chris Alcock &raquo; The Morning Brew #267
on 01-19-2009 3:01 AM

Pingback from  Reflective Perspective - Chris Alcock  &raquo; The Morning Brew #267

Andrew wrote re: Language Envy - String Interpolation
on 01-19-2009 3:50 PM

@Sergio

I know you were just kidding, but really in a given week, how much time would adding this feature save an average developer?  2 minutes? 5 minutes?

We all remember the one day where we use string.Format 100 times, but not all the other days where we don't use it at all.  I'm not saying it'd be a horrible a feature, but I'm also not waiting for it with baited breath either.

@George

If developers only used var in those situations, I'd be all for it...but we all know this isn't the case.  Don't you just love opening code and seeing:

var IsOpen = true;

instead of

bool IsOpen = true;

sergiopereira wrote re: Language Envy - String Interpolation
on 01-19-2009 3:59 PM

@Andrew, it is not all about saving time. It's about avoiding bugs and improving readability. Someone maintaining the code does not need to solve mental puzzles and count arguments to understand what string is being produced.

This feature is one of those things that once you use them, it's hard to let go of it. Think how you could do a lot with anonymous delegates in C# 2 and how much more we do with lambdas in C# 3, even though the latter are just syntactic sweetener over the former.

Andrew wrote re: Language Envy - String Interpolation
on 01-19-2009 6:12 PM

@Sergio,

While I'm all for readability of code, wouldn't finding variable names within a string be just as, if not more difficult than reading the current String.Format as it exsits today?   I'd say so.

Plus you wouldn't have intellisense and if you made a spelling mistake your code would compile yet error out at run time, etc. Granted (as you mentioned) Microsoft could do the work to VS to give you Intellisense and parse the string at compile time, but then aren't we talking a a lot of work for this small enchantment?

sergiopereira wrote re: Language Envy - String Interpolation
on 01-19-2009 7:52 PM

@Andrew,

I disagree with your points, but that's not important.

I'm just saying that this is a feature that many other languages have and I like a lot. I also don't see anyone asking for a String.Format in PHP or Ruby.

I'm not going to say this feature is more important than things like immutability, contracts, etc, but if anyone on the C# team happens to wander over here, maybe they'll see that there are some people that would thank them for adding string interpolation to the language (I'm sure they already know that.)

Per-Erik wrote re: Language Envy - String Interpolation
on 01-22-2009 4:41 AM

One big problem with embedding code in the strings is that things are much more likely to break after localization. Translators really don't like strange code noise in the strings.

sergiopereira wrote re: Language Envy - String Interpolation
on 01-22-2009 8:20 AM

@Per-Erik, that's an interesting point but in .NET, at least in my experience, localization works off external resources (.resx files, xml files, database, etc). That would not work with string interpolation anyway because it wouldn't be a compile time event.

If you use a different method of localization, which works at compile time, you probably don't want to use interpolation

.

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)