ヒント
この記事は、少なくとも 1 つのプログラミング言語を既に知っており、C# を学習している開発者向けの 基礎 セクションの一部です。 プログラミングを初めて使用する場合は、最初に「 はじめ に」チュートリアルから始めてください。
別の言語から来ていますか? C# での文字列補間は、JavaScript のテンプレート リテラル (`${x}`) やPythonの f 文字列 (f"{x}") とよく似ています。
{}内の式には任意の有効な C# 式を指定できます。また、文字列を残さずに書式指定子と配置指定子を追加できます。
文字列補間 を使用すると、リテラルの前に $ を付けることで、式を文字列リテラルに直接埋め込むことができます。
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);
// => 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
各 { } は 補間式です。 C# は式を評価し、 ToString() メソッドを呼び出して結果を文字列に変換し、テキストを結果に置き換えます。
null式の文字列補間は空の文字列です。 ほとんどの場合、既定の変換では必要な出力が生成され、それ以上何もする必要はありません。
挿入文字列は、 String.Formatの代わりに読みやすく、完全な 複合書式設定 機能セットをサポートします。 従来の位置指定書式指定文字列 (書式指定子、配置、カルチャ対応の書式指定、定数文字列) を使用してできることは、挿入文字列でも実行できます。 この記事の残りの部分では、これらのオプションについて説明します。 結果を細かく制御する必要がある場合にのみ、それらに到達します。それ以外の場合は、プレーンな $"{expression}" 形式で十分です。
構文と基になるハンドラー型の言語参照の処理については、 補間された文字列 参照を参照してください。
Span<char>補間やカスタム補間文字列ハンドラーなどのパフォーマンスに重点を置いたトピックについては、「文字列演算」を参照してください。
書式文字列を適用する
式の結果の書式設定方法を制御するには、コロンと 標準書式指定文字列またはカスタム書式指定文字列を使用して式に従います。
{<expression>:<formatString>}
次の例では、 DateTime と Double 値を書式設定します。
var date = new DateTime(1731, 11, 25);
Console.WriteLine($"On {date:dddd, MMMM dd, yyyy} L. Euler introduced the letter e to denote {Math.E:F5}.");
// => On Sunday, November 25, 1731 L. Euler introduced the letter e to denote 2.71828.
フィールドの幅と配置を設定する
配置された出力を生成するには、コンマと最小フィールド幅で式に従います。 正の幅は値を右揃えにし、負の幅は左揃えにします。
{<expression>,<width>}
var titles = new Dictionary<string, string>()
{
["Doyle, Arthur Conan"] = "Hound of the Baskervilles, The",
["London, Jack"] = "Call of the Wild, The",
["Shakespeare, William"] = "Tempest, The"
};
Console.WriteLine("Author and Title List");
Console.WriteLine();
Console.WriteLine($"|{"Author",-25}|{"Title",30}|");
foreach (var title in titles)
{
Console.WriteLine($"|{title.Key,-25}|{title.Value,30}|");
}
// => Author and Title List
// =>
// => |Author | Title|
// => |Doyle, Arthur Conan |Hound of the Baskervilles, The|
// => |London, Jack | Call of the Wild, The|
// => |Shakespeare, William | Tempest, The|
配置と書式指定文字列の両方が必要な場合は、最初に配置を配置します。
{<expression>,<width>:<formatString>}
const int NameAlignment = -9;
const int ValueAlignment = 7;
double a = 3;
double b = 4;
Console.WriteLine($"Three classical Pythagorean means of {a} and {b}:");
Console.WriteLine($"|{"Arithmetic",NameAlignment}|{0.5 * (a + b),ValueAlignment:F3}|");
Console.WriteLine($"|{"Geometric",NameAlignment}|{Math.Sqrt(a * b),ValueAlignment:F3}|");
Console.WriteLine($"|{"Harmonic",NameAlignment}|{2 / (1 / a + 1 / b),ValueAlignment:F3}|");
// => Three classical Pythagorean means of 3 and 4:
// => |Arithmetic| 3.500|
// => |Geometric| 3.464|
// => |Harmonic | 3.429|
書式設定された値が要求された幅よりも長い場合、C# は幅を無視し、完全な値を出力します。
中かっこをエスケープし、エスケープ シーケンスを使用する
挿入文字列は、通常の文字列リテラルと同じエスケープ シーケンスをサポートします。 リテラル { または } 文字を結果に含めるには、2 倍にします ({{ または }})。
バックスラッシュを含むパスやそのほかの文字列には、従来の逐語形式 ($@"...") よりも 補間された生文字列リテラル ($"""...""") を優先します。 未加工の文字列リテラルはエスケープ シーケンスを処理しないため、バックスラッシュは as-is表示されます。
int[] xs = [1, 2, 7, 9];
int[] ys = [7, 9, 12];
Console.WriteLine($"Find the intersection of the {{{string.Join(", ", xs)}}} and {{{string.Join(", ", ys)}}} sets.");
// => Find the intersection of the {1, 2, 7, 9} and {7, 9, 12} sets.
var userName = "Jane";
var stringWithEscapes = $"C:\\Users\\{userName}\\Documents";
var rawInterpolated = $"""C:\Users\{userName}\Documents""";
Console.WriteLine(stringWithEscapes);
Console.WriteLine(rawInterpolated);
// => C:\Users\Jane\Documents
// => C:\Users\Jane\Documents
条件式を使用する
コロンは補間式内では特別な意味を持つため、条件式をかっこで囲みます。
var rand = new Random(42);
for (int i = 0; i < 3; i++)
{
Console.WriteLine($"Coin flip: {(rand.NextDouble() < 0.5 ? "heads" : "tails")}");
}
式を複数行にまたがって記述する
読みやすくするために、長い補間式を複数の行にわたって分割します。 C# 11 以降では、複数行補間式を使用できます。 次の例では、 { 文字と } 文字の間に改行を追加して、挿入された式をリテラル テキストから分離します。
int[] numbers = [3, 1, 4, 1, 5, 9, 2, 6];
Console.WriteLine($"Total: {
numbers.Sum()
}, average: {numbers.Average():F2}.");
// => Total: 31, average: 3.88.
定数文字列をビルドする
すべての補間式が定数値である場合は、定数補間文字列を作成できます。これにより、属性引数、 switch パターン、コンパイル時定数を必要とするその他のコンテキストで使用できます。
const string Audience = "world";
const string Greeting = $"Hello, {Audience}!";
Console.WriteLine(Greeting);
// => Hello, world!
特定のカルチャを使用して書式設定する
既定では、挿入文字列は、日付、数値、通貨表現に影響を与える CultureInfo.CurrentCultureを使用して値を書式設定します。 確定的な出力の場合は、明示的なカルチャを String.Create(IFormatProvider, DefaultInterpolatedStringHandler)に渡します。
CultureInfo[] cultures =
[
CultureInfo.GetCultureInfo("en-US"),
CultureInfo.GetCultureInfo("en-GB"),
CultureInfo.GetCultureInfo("nl-NL"),
CultureInfo.InvariantCulture
];
var date = new DateTime(2026, 5, 21, 12, 35, 31);
var number = 31_415_926.536;
foreach (var culture in cultures)
{
var cultureSpecificMessage = string.Create(culture, $"{date,23}{number,20:N3}");
Console.WriteLine($"{culture.Name,-10}{cultureSpecificMessage}");
}
// Output is similar to:
// => en-US 5/21/2026 12:35:31 PM 31,415,926.536
// => en-GB 21/05/2026 12:35:31 31,415,926.536
// => nl-NL 21-05-2026 12:35:31 31.415.926,536
// => 05/21/2026 12:35:31 31,415,926.536
インバリアント出力 (ログ、ファイル形式、コンピューターが読み取り可能なデータ) の場合は、 CultureInfo.InvariantCulture渡します。
var timestamp = new DateTime(2026, 5, 21, 15, 46, 24);
string message = string.Create(CultureInfo.InvariantCulture, $"Date and time in invariant culture: {timestamp}");
Console.WriteLine(message);
// => Date and time in invariant culture: 05/21/2026 15:46:24
こちらも参照ください
.NET