Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does '$' sign do in C# 6.0?

In MVC 6 source code I saw some code lines that has strings leading with $ signs.

As I never saw it before, I think it is new in C# 6.0. I'm not sure. (I hope I'm right, otherwise I'd be shocked as I never crossed it before.

It was like:

var path = $"'{pathRelative}'";
like image 342
Yves Avatar asked May 12 '15 15:05

Yves


People also ask

What is '$' in C?

@ is generally invalid in C; it is not used for anything. It is used for various purposes by Objective-C, but that's a whole other kettle of fish. $ is invalid as well, but many implementations allow it to appear in identifiers, just like a letter.

Why do we use percentage sign in C?

% is the modulo operator, so for example 10 % 3 would result in 1. If you have some numbers a and b , a % b gives you just the remainder of a divided by b . So in the example 10 % 3 , 10 divided by 3 is 3 with remainder 1, so the answer is 1.

What does the dollar sign do in programming?

In programming In languages like BASIC, Pascal, and PHP, the dollar sign defines variables and constants. ALGOL 68 and TeX typesetting languages use the dollar sign for delimiting transput format and mathematical regions. ASP.NET uses the dollar sign to indicate an expression.

What does %c mean in C?

%d is used to print decimal(integer) number ,while %c is used to print character . If you try to print a character with %d format the computer will print the ASCII code of the character.


1 Answers

You're correct, this is a new C# 6 feature.

The $ sign before a string enables string interpolation. The compiler will parse the string specially, and any expressions inside curly braces will be evaluated and inserted into the string in place.

Under the hood it converts to the same thing as this:

var path = string.Format("'{0}'", pathRelative);

Let's look at the IL for this snippet:

var test = "1";
var val1 = $"{test}";
var val2 = string.Format("{0}", test);

Which compiles to:

// var test = "1";
IL_0001: ldstr "1"
IL_0006: stloc.0

// var val1 = $"{test}";
IL_0007: ldstr "{0}"
IL_000c: ldloc.0
IL_000d: call string [mscorlib]System.String::Format(string, object)
IL_0012: stloc.1

// var val2 = string.Format("{0}", test);
IL_0013: ldstr "{0}"
IL_0018: ldloc.0
IL_0019: call string [mscorlib]System.String::Format(string, object)
IL_001e: stloc.2

So the two are identical in the compiled application.


A note on the C# string interpolation syntax: Unfortunately the waters are muddied right now on string interpolation because the original C# 6 preview had a different syntax that got a lot of attention on blogs early on. You'll still see a lot of references to using backslashes for string interpolation, but this is no longer syntactically valid.

like image 200
pauljz Avatar answered Oct 03 '22 08:10

pauljz