I'm working on a project and they gave me a C# file with code similar to what I had to do. Investigating it I found this:
valorOpcion1 = "valor_que_viene_de_un_lado";
valorOpcion2 = "valor_que_viene_de_otro_lado";
var miLista = new List<string>
{
$"opcion1:{valorOpcion1}",
$"opcion1:{valorOpcion2}"
};
What it does is define and initialize a list of strings with two default values. My doubt comes with the $
one with those chains, I don't know what it is.
What does putting the dollar sign ( $
) in front of a string do? Is there a difference between, say, "hola"
and $"hola"
?
It means that it is an interpolated string.
String interpolation means that you can use previously defined variables in your code, and the JIT compiler will take care of replacing them with the respective values at run time.
In your example, each of the options will have as value:
Interpolation allows you to call functions within the chain, for example:
And you can even use a ternary operator inside, to do a quick analysis:
The complete documentation is here
In
C#
there are two types of symbols to format a stringstrings
directly.Previously, the Composite String format was used , making it use unidentifiable arguments and making the process of formatting a string more tedious.
Let's use the following example class:
Using the
Formato Compuesto
, to form a string with the person values you would have to do the following:If you notice,
Formato Compuesto
it is guided by indexes, which does not give you clarity of what value is being used if you do not know the order. So using the format ofCadena Interpolada
, the format is direct and you already know the assigned property:For example, if I want to print quotes in a
string
, I must insert the symbol\
in between, which means that the will\
not be part of the result. If I want to make the symbol\
part of the result, I must use theIdentificador textual
:You can see more examples in the attached official documentation.
What is?
$
is a shortcut forString.Format
and is used with string interpolations.Using it on the string
"hola"
would not modify anything, just like usingString.Format("hola")
. Now in the case you show in your code:What it does is put the values of
valorOpcion1
yvalorOpcion2
, inside the string.