Frage

So a bit of a weird question I was having trouble coming up with the search terms for. If I have a multi-line string literal in my program, is there anyway to keep the indentation of my code consistent without adding unwanted white space to my string literal?

Ex:

if (true)
{
    if (!false)
    {
        //Some indented code;
        stringLiteral = string.format(
@"This is a really long string literal
I don't want it to have whitespace at 
the beginning of each line, so I have
to break the indentation of my program
I also have vars here 
{0}
{1}
{2}",
var1, var2, var3);
    }
}

It's probably just my OCD talking, but is there anyway to maintain the indentation of my program without adding unwanted whitespace to the string, or having to build it line by line (the real string is a super long string.format that is 20~ lines with 12 variables inside)?

War es hilfreich?

Lösung

I would abstract it to a separate static class or resource completely:

public static class MyStringResources
{
    public static readonly string StringLiteral = 
@"This {0} a really long string literal
I don't want {1} to have {2} at 
the beginning of each line, so I have
to break the indentation  of my program";

}

With usage like:

stringLiteral = String.Format(MyStringResources.StringLiteral, var1, var2, var3);

Even better, this way you can have a nice function that requires the number of expected variables:

public static class MyStringLiteralBuilder
{
    private static readonly string StringLiteral = 
@"This {0} a really long string literal
I don't want {1} to have {2} at 
the beginning of each line, so I have
to break the indentation  of my program";

    public static string Build(object var1, object var2, object var3)
    {
        return String.Format(MyStringResources.StringLiteral, var1, var2, var3);
    }
}

Then you can't miss variables accidentally (and possibly even strongly type them to numbers, booleans, etc.)

stringLiteral = MyStringLiteralBuilder.Build(var1, var2, var3);
stringLiteral = MyStringLiteralBuilder.Build(var1, var2); //compiler error!

Of course at this point, you can do pretty much whatever you want with these builders. Make a new builder for each special big "stringLiteral" you have in your program. Maybe instead of having them static they can be instances that you can get/set the key properties, then you can give them nice names too:

public class InfoCardSummary
{
    public string Name { get; set; }
    public double Age { get; set; }
    public string Occupation { get; set; }

    private static readonly string FormattingString = 
@"This person named {0} is a pretty
sweet programmer. Even though they're only
{1}, Acme company is thinking of hiring
them as a {2}.";

    public string Output()
    {
        return String.Format(FormattingString, Name, Age, Occupation);
    }
}

var info = new InfoCardSummary { Name = "Kevin DiTraglia", Age = 900, Occupation = "Professional Kite Flier" };
output = info.Output();

Andere Tipps

In my case it was acceptable to make an extension method like this:

class Program
{
    static void Main(string[] args)
    {
        var code = $@"
            public static loremIpsum(): lorem {{
                return {{
                    lorem: function() {{
                        return 'foo'
                    }},
                    ipsum: function() {{
                        return 'bar'
                    }},
                    dolor: function() {{
                        return 'buzz'
                    }}
                }}
            }}".AutoTrim();

        Console.WriteLine(code);
    }
}

static class Extensions
{
    public static string AutoTrim(this string code)
    {
        string newline = Environment.NewLine;
        var trimLen = code
            .Split(newline)
            .Skip(1)
            .Min(s => s.Length - s.TrimStart().Length);

        return string.Join(newline,
            code
            .Split(newline)
            .Select(line => line.Substring(Math.Min(line.Length, trimLen))));
    }
}

enter image description here

Define your string constant in another file and use the identifier in your code. It is a good practice to have all your strings in one place anyway if you need them translated, reviewed for compliance, etc..

if (true)
{
    if (!false)
    {
        //Some indented code;
        stringLiteral = string.format(
                    "This is a really long string literal. " +
                    "I don't want it to have whitespace at " +
                    "the beginning of each line, so I have " +
                    "to break the indentation of my program " +
                    "I also have vars here: " +
                    "{0} " +
                    "{1} " +
                    "{2}",
                  var1, var2, var3);
          // OR, with lineskips:
        stringLiteral = string.format(
                    "This is a really long string literal\r\n" +
                    "I don't want it to have whitespace at \r\n" +
                    "the beginning of each line, so I have\r\n" +
                    "to break the indentation of my program\r\n"
                    "I also have vars here\r\n" +
                    "{0}\r\n" +
                    "{1}\r\n" +
                    "{2}\r\n",
                  var1, var2, var3);
    }
}

Not beautiful but it works.

Another "solution" is to wrap each such string in a #region and fold it. This does not really solve the problem, but at least it makes the code less of an eye-sore.

When combining @ verbatim strings and the newer $ string interpolation you could apply the following trick: within { and } it is an expression (hence code) and not string data. Put your newline and your indent there and it will not show up in the formatted string. If your text does not contain expressions you can replace a space by an ' ' expression where you want a line break.

using System;

namespace ConsoleApplication6
{
    class Program
    {
        static void Main()
        {
            int count = 123;
            Console.WriteLine($@"Abc {count} def {count
                } ghi {
                count} jkl{' '
                }mno");
            Console.ReadLine();
        }
    }
}

Output:

Abc 123 def 123 ghi 123 jkl mno

The grammar for the C# language allows two ways of specifing string literals:

  • A here-doc/at-string (@"..."), which may span source file lines, or
  • An ordindary string literal ("..."), which may not.

Other means of getting the effect you want:

  1. Put your strings into resource files. This makes localization easier down the line.

  2. Add them to your assembly as embedded (file) resources:

An alternative, in the vein of other answers trying make it look nicer:

static readonly string MultilineLiteral = string.Join( Environment.NewLine , new string[]{
                                          @"line 1" ,
                                           "line 2" ,
                                          @"line 3" ,
                                          . . .
                                          "line n" ,
                                          }) ;

I, too have come across this problem.

Some times I put the entire thing on one line with \n (or \r\n for dos/windows).

Some times, I just ignore the ugly code formatting.

Other times, I put the text elsewhere - I think in c# you have #define, or even in a separate file or database, depending on the string in question. You still have to replace the variable - in c# I think you use string.Format?

I hope this is enough to get you started on a solution.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top