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