LoginSignup
5
3

More than 1 year has passed since last update.

C#で文字列の中に変数を埋め込む

Last updated at Posted at 2023-01-30

1. はじめに

  • C# 6.0から使用できるようになった文字列補間式を使用したい

  • 追記

  • C# 10からは補間文字列($"")をAppendFormattedやAppendLiteralメソッドに展開するようになっています。詳細は以下記事を参照。(@junerさんよりご教授いただいた)

2. 文字列補間式とは

  • C# 5.0まではstring.Formatで指定した変数の埋め込みを文字列保管式$を使って簡易的に記述できる

3. 文字列保管式の書き方

3.1. 文字列補間式 使用前

C#
var param = "pen";
Debup.Print("This is a {0}.", parm);

3.2. 文字列補間式 使用後

C#
var param = "pen";
Debup.Print($"This is a {data}.");

4. 文字列補間式の特徴

4.1. コンパイルエラーとして検知できる

  • string.Formatでは気づけない実行時エラーをコンパイルエラーとして検知できる

4.2. 書式が設定できる

  • string.Formatと同様に書式が設定できる
C#
var now = DateTime.Now;
Console.WriteLine($"{now:yyyyMMdd}");  // "2018年04月01日"

var today = DateTime.Today;
Console.WriteLine($"{today.Year}{today.Month,2}{today.Day,2}");   // "2018年 4月 1日"

var num1 = 1234567890;
Console.WriteLine($"{num1:#,0}");   // "1,234,567,890"

var num2 = 123;
Console.WriteLine($"{num2:00000}");  // "00123"

4.3. エスケープもできる

  • {を出力したい場合は{{と記述する
C#
var framework = "Angular";
Console.WriteLine($"{framework}のデータバインドは{{{{}}}}と書きます");
    // "Angularのデータバインドは{{}}と書きます"

5. 参考文献

5
3
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3