Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new line in a multi-line string

Trying to override a tostring in one of my classes.

 return string.Format(@" name = {0}
                         ID = {1}
                         sec nr = {2}
                         acc nr = {3}", string, int, int ,int); // types

But the thing is, the result isn't aligned when printed out:

name = test
                                   ID = 42
                                   sec nr = 11
                                   acc nr = 55

Trying to add \n just prints it out without formating. Guessing it has something to do with @"" which I'm using for multi-lining.

Would like it to print out :

name = test
ID = 42
sec nr = 11
acc nr = 55
like image 306
Milan Avatar asked Apr 13 '10 09:04

Milan


People also ask

Can a string have multiple lines?

They are called Raw Strings. They can span multiple lines without concatenation and they don't use escaped sequences. You can use backslashes or double quotes directly. For example, in Kotlin, in addition to regular string literals, you can use Raw Strings with three double quotes """ instead of just one.


2 Answers

The @ before the string switches off standard C# string formatting, try

 return string.Format(" name = {0}\n ID = {1} \n sec nr = {2} \n acc nr = {3}", 
                      string, int, int ,int); // types

You can't use the @ and use \n, \t etc.

EDIT

This is - IMHO - as good as it gets

 return string.Format("name = {0}\n" + 
                      "ID = {1}\n" + 
                      "sec nr = {2}\n" + 
                      "acc nr = {3}", 
                       string, int, int ,int); 
like image 141
Binary Worrier Avatar answered Sep 22 '22 11:09

Binary Worrier


If you add spaces in front, it will be printed that way.

I normally do it like this.

   return string.Format(
@" name = {0}
 ID = {1}
 sec nr = {2}
 acc nr = {3}", string, int, int ,int); // types

Update: Perhaps a prettier alternative:

string[] lines = 
{
  " name = {0}",
  " ID = {1}",
  " sec nr = {2}",
  " acc nr = {3}"
};

return string.Format(
         string.Join(Environment.Newline, lines), 
         arg0, arg1, arg2, arg3);
like image 32
leppie Avatar answered Sep 20 '22 11:09

leppie