1. はじめに
- C#で変数の文字列をセットする時に、たまに
$(ドルマーク)
が先頭にある理由を知りたい
2. 開発環境
- C#
- .Net 6
- Visual Studio 2022
- Windows 11
3. $(ドルマーク)がある理由
- C#6.0から追加されたString interpolation(文字列補間)を使用するため
- 以下、Microsoft社のHPのサンプルソースコードがわかりやすい
double a = 3;
double b = 4;
Console.WriteLine($"Area of the right triangle with legs of {a} and {b} is {0.5 * a * b}");
Console.WriteLine($"Length of the hypotenuse of the right triangle with legs of {a} and {b} is {CalculateHypotenuse(a, b)}");
double CalculateHypotenuse(double leg1, double leg2) => Math.Sqrt(leg1 * leg1 + leg2 * leg2);
// Expected output:
// Area of the right triangle with legs of 3 and 4 is 6
// Length of the hypotenuse of the right triangle with legs of 3 and 4 is 5
4. 参考文献