6

Is there any way to interpolate variable several times without repeating?

For example:

var name = "bla";
Console.WriteLine($"foo {name:repeat:2} bar")

to print

foo blabla bar

I'm particularly interested in interpolating several line breaks instead of repeating {Environment.NewLine} several times in the interpolation mask like this:

$"{Environment.NewLine}{Environment.NewLine}"
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
Illia Ratkevych
  • 3,507
  • 4
  • 29
  • 35
  • 1
    Maybe take a look at this. Maybe combine with String.Format https://stackoverflow.com/questions/411752/best-way-to-repeat-a-character-in-c-sharp – RichyP7 Nov 14 '18 at 17:28

3 Answers3

10
public static string Repeat(this string s, int times, string separator = "")
{
    return string.Join(separator, Enumerable.Repeat(s, times));
}

Then use:

Console.WriteLine($"foo {name.Repeat(2)} bar")
eocron
  • 6,885
  • 1
  • 21
  • 50
  • I thought it could have been some out-of-the-box option for string interpolation. But if not your solution looks like the simplest alternative. Thanks – Illia Ratkevych Nov 14 '18 at 21:52
1

You could write an extension method for the string type, thats repeating its input. Then simply use this method within the curly braces.

Grimm
  • 690
  • 8
  • 17
0

You could also use

var name = "bla";
Console.WriteLine("foo {0}{0} bar", name);
// or
var s = String.Format("foo {0}{0} bar", name);

It will help you not repeating the same string, just index of it.

More about String Format

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69