What does $ mean before a string?
I was going to use verbatim string but i mistakenly typed $
instead of @
.
But the Compiler didn't give me any Error and Compiled successfully.
I want to know what it is and what it does. I searched for it but i couldn't find anything.
However it is not like a verbatim string because I can't write:
string str = $"text\";
Does anyone know what $
before string stand for in C#.
string str = $"text";
I'm using Visual studio 2015 CTP.
$
is short-hand for String.Format
and is used with string interpolations, which is a new feature of C# 6. As used in your case, it does nothing, just as string.Format()
would do nothing.
It is comes into its own when used to build strings with reference to other values. What previously had to be written as:
var anInt = 1;
var aBool = true;
var aString = "3";
var formated = string.Format("{0},{1},{2}", anInt, aBool, aString);
Now becomes:
var anInt = 1;
var aBool = true;
var aString = "3";
var formated = $"{anInt},{aBool},{aString}";
There's also an alternative - less well known - form of string interpolation using $@
(the order of the two symbols is important). It allows the features of a @""
string to be mixed with $""
to support string interpolations without the need for \\
throughout your string. So the following two lines:
var someDir = "a";
Console.WriteLine($@"c:\{someDir}\b\c");
will output:
c:\a\b\c
It creates an interpolated string.
From MSDN
Used to construct strings. An interpolated string expression looks like a template string that contains expressions. An interpolated string expression creates a string by replacing the contained expressions with the ToString represenations of the expressions’ results.
ex :
var name = "Sam";
var msg = $"hello, {name}";
Console.WriteLine(msg); // hello, Sam
You can use expressions within the interpolated string
var msg = $"hello, {name.ToLower()}";
Console.WriteLine(msg); // hello, sam
The nice thing about it is that you don't need to worry about the order of parameters as you do with String.Format
.
var s = String.Format("{0},{1},{2}...{88}",p0,p1,..,p88);
Now if you want to remove some parameters you have to go and update all the counts, which is not the case anymore.
Note that the good old string.format
is still relevant if you want to specify cultural info in your formatting.