RunningCSharp

MS系開発者による、雑多な記事。記事は所属企業とは関係のない、個人の見解です。

C#:補完文字列に関するTips

C#4.6以降で使える補完文字列でも、改行や\をそのまま扱いたいときは@が使えます。

string test = $@"C:\test
D:\test";

また、補完対象の中括弧内に関数を指定する事も可能でした。

string test1 = "test1";
string interpolation = "補完したい文字列:{func(test1)}";
… 
static string func(string teststr) => teststr + "add";

更に中括弧内で使う関数の引数に文字列リテラルを使用することも可能で、更にその文字列リテラルに$を付けて補完文字列を扱えるなど、非常に柔軟な仕様のようです。

string test1 = "and";
string interpolation = $"{func(@"\te" + $"st{test1}")}";
Console.WriteLine(interpolation);
… 
static string func(string teststr) => teststr + "add";

結果

\testandadd