Search code examples
c#stringindentationrawstring

how to preserve indent inside triple quote in C# 11?


In C#, using triple quotes ("""), how could I preserve the inner indentation of the second triple quotes? here it is a fiddle https://dotnetfiddle.net/ypP8Xp

EDIT: This is only an example, I always need the same indent before each line in Text2, no matter the inner text, so is not an option to modify inner text with more tabs.

public static void Main(string[] args){
    Console.WriteLine(Text);
    Console.WriteLine("\n Expected:\n");
    Console.WriteLine(Expected);
}
    
public static string Text => $"""
        I have 4 spaces
        {Text2}         
    """;
        
public static string Text2 => """
        I have 8 spaces
            I should have 12, why not?
    """;
        
public static string Expected => """
        I have 4 spaces
            I have 8 spaces
                I have 12 spaces
    """;

enter image description here


Solution

  • After some comments I realized that Text2 is "pasted" with its own indent, I thought that some already functions could be used to formatted it, so, until some other efficient answer appears, I will add the indent manually to children as I could know how many spaces I need from parents.

    public static string Text => $"""
        I have 4 spaces
        {Text2.InnerIndent(4)}          
    """;
                
    public static string Text2 => """
        I have 8 spaces
            I should have 12, why not?
    """;
                
    public static string InnerIndent(this string value, int indent) =>
        string.Join($"\n{new string(' ', indent)}", value.Split('\n'));