Search code examples
c#stringrawstring

Prevent new-line characters in a multiline raw string literal


How can I define raw string literal where the line breaks in the code are just for readability and there are no new-line characters (\r, \n) in the resulting string?

Something like this:

string str =
    """
    first line;
    also first line
    """;

should result in "first line;also first line".

So far this is what I've come up with, but it's pretty ugly:

str =
    $"""
    first line;{""
    }also first line
    """;

At least it's a bit less verbose than:

str =
    """
    first line;
    """ +
    """
    also first line
    """;

A popular LLM told me that in C# I can just use \ at the very end of a line in a raw string literal in order to prevent new-line characters, but that doesn't seem to work because the backslash just gets treated literally.


Solution

  • public static class StringExtensions
    {
        public static string WithoutNewlines(this string input)
        {
            return input.Replace("\n", "").Replace("\r", "");
        }
    }
    
    public static void Main()
    {
        string str =
        """
        first line;
        also first line
        """.WithoutNewlines();
        
        Console.WriteLine(str);
    }