Discussion:
interpolation in strings
(too old to reply)
Stefan Ram
2017-04-24 08:03:16 UTC
Permalink
I read a blog entry. It said something like:
»No. You can try all you want to, but /every/
expression is a allowed as an interpolation-expression.«.

I hit a "forbidden expression" on one of my first uses of
string interpolation.

public static class Program
{ public static void Main()
{ global::System.Console.WriteLine
( $"global::System.Math.PI = {global::System.Math.PI}." ); }}

Program.cs(4,35): error CS0103: The name 'global' does not exist in the current context

. The »:« might be interpreted as the begin of an
optional-colon-format. In fact, a work-around is:

public static class Program
{ public static void Main()
{ global::System.Console.WriteLine
( $"global::System.Math.PI = {(global::System.Math.PI)}." ); }}

global::System.Math.PI = 3.14159265358979.
Stefan Ram
2017-04-24 08:31:46 UTC
Permalink
Post by Stefan Ram
. The »:« might be interpreted as the begin of an
public static class Program
{ public static void Main()
{ global::System.Console.WriteLine
( $"global::System.Math.PI = {(global::System.Math.PI)}." ); }}
But now, "global::System.Math.PI = "+global::System.Math.PI+"."
achieves the same without interpolation, and is actually
shorter by one character (the initial »$«).
Arne Vajhøj
2017-04-24 18:27:47 UTC
Permalink
Post by Stefan Ram
Post by Stefan Ram
. The »:« might be interpreted as the begin of an
public static class Program
{ public static void Main()
{ global::System.Console.WriteLine
( $"global::System.Math.PI = {(global::System.Math.PI)}." ); }}
But now, "global::System.Math.PI = "+global::System.Math.PI+"."
achieves the same without interpolation, and is actually
shorter by one character (the initial »$«).
The purpose of all these features are to make the code more
readable.

So:

Console.WriteLine("Math.PI = " + Math.PI + ".");

versus:

Console.WriteLine("Math.PI = {Math.PI}.");

Arne
Real Troll
2017-04-25 04:30:00 UTC
Permalink
Post by Stefan Ram
Post by Stefan Ram
. The »:« might be interpreted as the begin of an
public static class Program
{ public static void Main()
{ global::System.Console.WriteLine
( $"global::System.Math.PI = {(global::System.Math.PI)}." ); }}
But now, "global::System.Math.PI = "+global::System.Math.PI+"."
achieves the same without interpolation, and is actually
shorter by one character (the initial »$«).
You could also do it like this:

using System;

namespace Stefan_Ram
{
class Program
{
static void Main(string[] args)
{
var myPI = Math.PI;
// First Method
Console.WriteLine($"myPI = {myPI}");

// Second Method
Console.WriteLine("myPI = {0}", myPI);

}
}
}

Continue reading on narkive:
Loading...