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)?
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();