C# $”{}”(文字列補間式)を使用して簡潔に記述する

  • 作成日 2021.11.18
  • 更新日 2022.04.01
  • C#
C# $”{}”(文字列補間式)を使用して簡潔に記述する

C#で、$”{}”(文字列補間式)を使用して簡潔に記述するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Microsoft Visual Studio Community 2019 Version 16.7.1

$”{}”使い方

$”{}”を使用すると、string.formatを使用せずに文字列内に変数を埋め込むことが可能です。

$"{変数名}"

以下は、$”{}”を使用して、文字列内に変数を埋め込むコードとなります。

using System;

namespace testapp
{
    class Program
    {
        static void Main(string[] args)
        {

            string str = "hello";
            Console.WriteLine($"strは{str}です。");
            // strはhelloです。            

            Console.ReadKey();

        }
    }
}

実行結果