Heredoc in C-sharp (C#)

Heredocs are very useful when embedding string-literal text in code. The C# syntax is to start a quote with an @ sign, like so:

string hereDocExample = @"Here is an example string in heredoc
 
   notice the formatting
 
           doesn't interpret nt
 
fun";
 
System.Console.WriteLine(hereDocExample);

Results in:

 
Here is an example string in heredoc
 
   notice the formatting
 
           doesn't interpret nt
 
fun

It’s obviously immediately useful for pre-formated output, but I’ve found it useful for other things like mini templates in small snippets of code. Here is a simple String.Format example:

 
string miniTemplate = @"Hello {0},
 
Your friend {1} sent you this message:
 
{2}
 
That's all!";
 
string populatedTemplate = String.Format(miniTemplate, "Fred", "Jack", "HelloWorld!");
 
System.Console.WriteLine(populatedTemplate);

Results in:

Hello Fred,
 
Your friend Jack sent you this message:
 
HelloWorld!
 
That's all!

References:

One Response to “Heredoc in C-sharp (C#)”

  1. rk says:

    Nice heredoc summary, especially using it in String.Format(); I wouldn’t have thought of that immediately.

Leave a Reply