Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long string interpolation lines in C#6

Tags:

c#

c#-6.0

I've found that while string interpolation is really nice when applied to my existing code base's string Format calls, given the generally preferred column limit, the string rapidly becomes too long for a single line. Especially when the expressions being interpolated are complex. With a format string you have a list of variables that you can split into multiple lines.

var str = string.Format("some text {0} more text {1}",
    obj1.property,
    obj2.property);

Does anyone have any preferred means of breaking up these lines?

I suppose you could do something like:

var str = $"some text { obj1.property }" +
  $" more text { obj2.property };
like image 760
Jeremiah Gowdy Avatar asked Oct 03 '22 12:10

Jeremiah Gowdy


People also ask

What is string interpolation in C?

In computer programming, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.

How do I write a multi line string literal in C?

We can use string literal concatenation. Multiple string literals in a row are joined together: char* my_str = "Here is the first line." "Here is the second line."; But wait!

What is meant by string interpolation?

An interpolated string is a string literal that might contain interpolation expressions. When an interpolated string is resolved to a result string, items with interpolation expressions are replaced by the string representations of the expression results.

Is string interpolation slow?

The following is a simple code I have, with a bunch of “for loops” with 100,000 iterations for each test: And I was really surprised to see that interpolation is the slowest of all. String concat with '+' took: 2,090 milliseconds. String Builder took: 1 milliseconds.


1 Answers

You can break the line into multiple lines, but I wouldn't say the syntax looks nice any more.

You need to use the $@ syntax to use an interpolated verbatim string, and you can place newlines inside the {...} parameters, like this:

string s = $@"This is all {
    10
    } going to be one long {
    DateTime.Now
    } line.";

The string above will not contain any newlines and will actually have content like this:

This is all 10 going to be one long 01.08.2015 23.49.47 line.

(note, norwegian format)

Now, having said that, I would not stop using string.Format. In my opinion some of these string interpolation expressions looks really good, but more complex ones starts to become very hard to read. Considering that unless you use FormattableString, the code will be compiled into a call to String.Format anyway, I would say keep going with String.Format where it makes sense.

like image 228
Lasse V. Karlsen Avatar answered Oct 16 '22 21:10

Lasse V. Karlsen