Search code examples
c#string-interpolation

Optimal Environment.Newline in interpolated string


I wanted to insert multiple new lines in a string so I used an interpolated string as my choice of a format mechanism which should be pretty fast.

Example:

string mystring = $"one line{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}another line{Environment.NewLine}end";

Now that works but how can I better insert multiple Environment.Newline in an interpolated string; for example if I wanted 15 this gets cumbersome.

I am aware of string.Replace(, string.Format(), and concatenation Environment.NewLine + Environment.NewLine + Environment.NewLine as well as literal string @"stuff" with blank lines however is not the question (an alternative) but rather how to insert multiples such my fake example of

string mystring = $"one line{Environment.NewLine(3)}another line{Environment.NewLine}end text";


Solution

  • Maybe not the most elegant solution, but you can call a method from within an interpolated string. The method can return a specified number of new lines.

    private string NewLines(int lines)
    {           
     return new StringBuilder().Insert(0,$"{Environment.NewLine}, lines").ToString();
    }
    

    Then just call

    string mystring = $"one line{NewLines(3)}another line{NewLines(1)}end text";