TL;DR: Add a C# new line with \n inside a string or with Console.WriteLine(). Use Environment.NewLine when the line ending should match the operating system, and encode text before converting new lines to <br/> in ASP.NET.

Almost every program needs to print or store text across multiple lines, whether it's console output, a report, a log file, or a message shown on a web page. Different programming languages handle line breaks differently, and C# gives you several options, each suited to a different situation.

This guide covers every common way to add a C# new line (sometimes searched as C # new line), with code that you can run and its real output. You'll also learn how new lines differ between Windows and Linux, how to write them to files, how to remove or replace them, and how to show them correctly in ASP.NET.

What Is the New Line Character in C#?

The new line character in C# is \n, called the line feed (LF), with character code 10. It tells the console, a text file, or any other output to continue on the next line.

There's a second line-ending character, \r, called the carriage return (CR), with the code 13. The names come from typewriters: the carriage return moved the print head back to the start of the line, and the line feed advanced the paper by one line. Today, operating systems use them differently:

  • Windows ends lines with \r\n (CR followed by LF).
  • Linux and macOS end lines with \n alone.

Most modern programs, including the Windows console, display both endings correctly. The difference matters mostly when you write files, compare strings, or exchange data between systems.

AI-Powered Full Stack Developer ProgramExplore Program
Want a Top Software Development Job? Start Here!

C# New Line Escape Characters

An escape character is a backslash followed by a letter or code that stands for a character you can't type directly into a string. These are the C# new line escape sequences:

Escape sequence

Name

Character code

What it does

\n

Line feed (LF)

10

Starts a new line; the standard on Linux and macOS

\r

Carriage return (CR)

13

Moves to the start of the current line

\r\n

CR followed by LF

13, 10

The standard line ending on Windows

\u000A

Unicode escape for LF

10

Same as \n, written as a Unicode code

\x0A

Hex escape for LF

10

Same as \n, but risky if a hex digit follows it

So what does \n mean in C#? It's simply the line feed character, and putting it inside a string splits the text onto two lines when you print the string.

How to Add a New Line in C#: Methods With Examples

Here are the most common ways to add a C# new line, starting with the simplest.

1. Using Console.WriteLine()

Does Console.WriteLine add a new line? Yes. It prints your text and then a line terminator, so the next output starts on a new line. Calling it with no arguments prints just the line terminator, which gives you a blank line.

using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello I am a Coder.");
            Console.WriteLine();
            Console.WriteLine("I code in C#");
        }
    }
}

Output:

Hello I am a Coder.

I code in C#

[Image retained: C_Sharp_New_Line_1]

The line terminator is stored in Console.Out.NewLine, and you can change it. In this example, every WriteLine() call ends with two line breaks instead of one:

using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            // Every WriteLine() call now ends with two line breaks
            Console.Out.NewLine = Environment.NewLine + Environment.NewLine;
            Console.WriteLine("Hello I am a Coder.");
            Console.WriteLine();
            Console.WriteLine("I code in C#");
        }
    }
}

Output:

Hello I am a Coder.



I code in C#

There are now three blank lines between the two sentences, not two. The first sentence ends with two line breaks, and the empty WriteLine() adds two more. The setting affects every later WriteLine() call in the program, so use it sparingly.

If you don't want a line break, use Console.Write() instead, which prints text without adding a new line.

2. Using the \n Escape Sequence

To insert a line break inside a C# string, place \n exactly where you want the new line to begin.

using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello I am a Coder.\nI code in C#");
        }
    }
}

Output:

Hello I am a Coder.
I code in C#

This is the quickest way to print a new line in C#, and it works on every platform. Be careful not to leave a space before \n, because it ends up as an invisible trailing space at the end of the line.

3. Using Environment.NewLine

Environment.NewLine is a property that returns the line ending for the operating system your program is running on: \r\n on Windows and \n on Linux and macOS. Using it means your output follows the platform's convention without any extra code.

using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello I am a Coder" + Environment.NewLine + "I code in C#");
        }
    }
}

Output:

Hello I am a Coder
I code in C#

Environment.NewLine is also what Console.WriteLine() and StringBuilder.AppendLine() add by default.

AI-Powered Full Stack Developer ProgramExplore Program
Here's How to Land a Top Software Developer Job

4. Using Hex and Unicode Escapes (\x0A and \u000A)

The character code for the line feed is 10, which is 0A in hexadecimal. You can write it as \x0A or \u000A, and both produce the same result as \n.

using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            // \x0A and \u000A are both the line feed character (ASCII 10)
            Console.WriteLine("Hello I am a Coder\x0AI code in C#");
            Console.WriteLine("Hello I am a Coder\u000AI code in C#");

            // Pitfall: \x reads up to four hex digits
            string broken = "Line\x0ABC";
            Console.WriteLine($"{broken.Length} characters, last one is U+{(int)broken[^1]:X4}");
        }
    }
}

Output:

Hello I am a Coder
I code in C#
Hello I am a Coder
I code in C#
5 characters, last one is U+0ABC

The last line shows why \x is risky. A \x escape reads up to four hex digits, so in "Line\x0ABC", C# reads \x0ABC as a single, unrelated character (U+0ABC) instead of a new line followed by "BC". The \u escape always takes exactly four digits, so \u000A is the safer choice. In most code, plain \n is clearer than either.

5. Using \r\n (Carriage Return and Line Feed)

What is \r\n in C#? It's the two-character Windows line ending: a carriage return followed by a line feed.

using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello I am a Coder\r\nI code in C#");
        }
    }
}

Output:

Hello I am a Coder
I code in C#

Use \r\n when a file format or protocol requires it regardless of the operating system, such as HTTP headers, email (SMTP), and CSV files meant for Windows tools—otherwise, \n or Environment.NewLine is usually the better choice.

6. Using StringBuilder.AppendLine()

When you build text from many pieces, such as a report or an email body, StringBuilder is faster than joining strings with + over and over. Its AppendLine() method adds text followed by Environment.NewLine, and calling it with no arguments adds a blank line.

using System;
using System.Text;

class Program
{
    static void Main()
    {
        StringBuilder report = new StringBuilder();
        report.AppendLine("Monthly Report");
        report.AppendLine("--------------");
        report.AppendLine("Orders: 128");
        report.AppendLine();               // adds a blank line
        report.Append("Status: ").Append("Complete").AppendLine();

        Console.Write(report.ToString());
    }
}

Output:

Monthly Report
--------------
Orders: 128

Status: Complete

You can also chain Append() calls and finish with AppendLine() to end the line.

7. Adding a New Line With String Interpolation

String interpolation lets you put variables directly into a string with $"...". To add a new line with string interpolation in C#, you can use \n, place Environment.NewLine inside the braces, or use a verbatim interpolated string ($@"...") and type a real line break.

using System;

class Program
{
    static void Main()
    {
        string name = "Asha";
        int orders = 3;

        // \n inside an interpolated string
        Console.WriteLine($"Customer: {name}\nOrders: {orders}");

        // Environment.NewLine inside the braces
        Console.WriteLine($"Customer: {name}{Environment.NewLine}Orders: {orders}");

        // Verbatim interpolated string: the line break in the code is kept
        Console.WriteLine($@"Customer: {name}
Orders: {orders}");
    }
}

Output:

Customer: Asha
Orders: 3
Customer: Asha
Orders: 3
Customer: Asha
Orders: 3

All three print the same result here. The Environment.NewLine version always uses the platform's line ending, while the verbatim version uses whatever line ending your source file was saved with.

Java Certification TrainingENROLL NOW
Dive Deep Into Java Core Concepts

8. Creating a Multiline String in C#

To create a multiline string in C#, you don't need any escape sequences. A verbatim string literal, written with @"...", keeps line breaks exactly as you type them. A raw string literal, written with three or more double quotes ("""), is available from C# 11 onward. It also removes the indentation in front of the closing quotes and lets you use double quotes without escaping them, which is ideal for JSON, SQL, or HTML.

using System;

class Program
{
    static void Main()
    {
        // Verbatim string literal: line breaks in the source are kept
        string address = @"Simplilearn
Bengaluru
India";
        Console.WriteLine(address);
        Console.WriteLine();

        // Raw string literal (C# 11 and later): indentation before the
        // closing quotes is removed, and quotes need no escaping
        string json = """
            {
              "course": "C#",
              "level": "Beginner"
            }
            """;
        Console.WriteLine(json);
    }
}

Output:

Simplilearn
Bengaluru
India

{
  "course": "C#",
  "level": "Beginner"
}

You can combine raw strings with interpolation as well, using $"""...""".

9. Using String.Join to Write Each String on a New Line

If you have a collection, such as a C# List, and want each item on its own line, string.Join() with Environment.NewLine as the separator does it in one call.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> steps = new List<string> { "Install .NET", "Create a project", "Run the app" };

        // Put each item on its own line
        string text = string.Join(Environment.NewLine, steps);
        Console.WriteLine(text);
    }
}

Output:

Install .NET
Create a project
Run the app

\n vs Environment.NewLine in C#

What is the difference between \n and Environment.NewLine in C#? \n is always the single line feed character, no matter where your program runs. Environment.NewLine changes with the operating system. You can see this by looking at the actual bytes each one produces. This output comes from Linux; on Windows, the Environment.NewLine line shows 0D-0A.

using System;
using System.Text;

class Program
{
    static void Main()
    {
        Console.WriteLine("\\n bytes:                " + BitConverter.ToString(Encoding.ASCII.GetBytes("\n")));
        Console.WriteLine("\\r\\n bytes:              " + BitConverter.ToString(Encoding.ASCII.GetBytes("\r\n")));
        Console.WriteLine("Environment.NewLine bytes: " + BitConverter.ToString(Encoding.ASCII.GetBytes(Environment.NewLine)));
        Console.WriteLine("Running on: " + Environment.OSVersion.Platform);
    }
}

Output:

\n bytes:                0A
\r\n bytes:              0D-0A
Environment.NewLine bytes: 0A
Running on: Unix

\n

Environment.NewLine

Value

Always \n

\r\n on Windows, \n on Linux and macOS

Type

Character in a string literal

Read-only property

Can be used in a const

Yes

No, because its value is only known at run time

Best for

Fixed formats, protocols, and quick console output

Files and text that should follow the local platform's convention

In practice, both display correctly in modern consoles and editors. Choose \n when you need the same output on every platform, and Environment.NewLine when the text should match the system it's running on.

Learn 45+ in-demand full-stack development skills and tools, including Frontend Development, Backend Development, Version Control and Collaboration, Database Management, and AI-Assisted Development, with our Full Stack Developer Course.

Writing New Lines to a Text File in C#

To write text on a new line in a file, use the File and StreamWriter classes from the System.IO namespace. File.WriteAllLines() writes each array item on its own line, File.AppendAllText() adds text to the end of a file, and StreamWriter.WriteLine() adds a line break after each call.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "notes.txt";

        // Writes each array item on its own line
        File.WriteAllLines(path, new[] { "First line", "Second line" });

        // Adds one more line to the end of the file
        File.AppendAllText(path, "Third line" + Environment.NewLine);

        // StreamWriter.WriteLine adds a line break after each call
        using (StreamWriter writer = new StreamWriter(path, append: true))
        {
            writer.WriteLine("Fourth line");
        }

        string[] lines = File.ReadAllLines(path);
        Console.WriteLine($"The file has {lines.Length} lines:");
        foreach (string line in lines)
        {
            Console.WriteLine(line);
        }
    }
}

Output:

The file has 4 lines:
First line
Second line
Third line
Fourth line

All of these use Environment.NewLine for line endings. When you append raw text yourself, as with File.AppendAllText(), remember to add the new line at the end, or the next write will continue on the same line.

Java Certification TrainingENROLL NOW
Take the Leap and Master Java Development

How to Remove or Replace New Lines in a C# String

Text that comes from users, files, or other systems often mixes \r\n and \n. To remove or replace new line characters in a C# string, the cleanest option is ReplaceLineEndings(), available from .NET 6 onward, which handles every kind of line ending at once. On older versions, use Replace(), and replace \r\n before \n so you don't leave stray \r characters behind.

using System;

class Program
{
    static void Main()
    {
        string text = "Line one\r\nLine two\nLine three";

        // Remove new lines by replacing them with a space (.NET 6 and later)
        Console.WriteLine(text.ReplaceLineEndings(" "));

        // Remove new lines with Replace(): handle \r\n before \n
        Console.WriteLine(text.Replace("\r\n", " ").Replace("\n", " "));

        // Delete new lines completely
        Console.WriteLine(text.ReplaceLineEndings(string.Empty));

        // Normalize mixed line endings to the current platform's new line
        string normalized = text.ReplaceLineEndings();
        Console.WriteLine(normalized.Contains("\r\n") ? "Uses \\r\\n" : "Uses \\n");

        // Split a string into lines
        string[] lines = text.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None);
        Console.WriteLine($"Line count: {lines.Length}");
    }
}

Output:

Line one Line two Line three
Line one Line two Line three
Line oneLine twoLine three
Uses \n
Line count: 3

Calling ReplaceLineEndings() with no arguments converts every line ending to Environment.NewLine. On Linux, as in this run, that's \n; on Windows, it's \r\n.

Want to expand your software development skills? Simplilearn’s Java Course helps you learn Java, Java EE, and service-oriented architecture concepts. Explore the course to build practical knowledge and strengthen your foundation for working with enterprise-level software applications.

Adding New Lines in ASP.NET

Browsers ignore \n and \r\n in normal HTML text and treat them as spaces. So if you show a user's comment that contains line breaks on a web page, it appears as one long line. There are two good ways to fix this.

The first is to convert the line breaks into <br/> tags. Always HTML-encode the text first; otherwise, a user could type a <script> tag and run code in other visitors' browsers. This extension method does both steps:

using System;
using System.Net;
using System.Text.RegularExpressions;

static class StringExtensions
{
    public static string ConvertToLineBreaks(this string inputString)
    {
        // Encode first, so user input can't inject HTML or scripts
        string encoded = WebUtility.HtmlEncode(inputString);

        // Then turn every kind of line ending into <br/>
        return Regex.Replace(encoded, @"\r\n|\r|\n", "<br/>");
    }
}

class Program
{
    static void Main()
    {
        string comment = "Great course!\r\nLoved the C# module.\n<script>alert('hi')</script>";
        string html = comment.ConvertToLineBreaks();
        Console.WriteLine(html);
    }
}

Output:

Great course!<br/>Loved the C# module.<br/>&lt;script&gt;alert(&#39;hi&#39;)&lt;/script&gt;

The line breaks have become <br/> tags, while the script tag has been encoded into harmless text. In a Razor view, output the result with @Html.Raw(comment.ConvertToLineBreaks()). This is safe only because the method encodes the text before adding the tags.

The second option, often simpler, is to leave the text as it is and let CSS display the line breaks:

<p style="white-space: pre-line;">@Model.Comment</p>

Razor encodes @Model.Comment automatically, and white-space: pre-line tells the browser to respect the line breaks while still wrapping long lines. Use pre-wrap instead if you also want to keep multiple spaces.

Which C# New Line Method Should You Use?

Situation

Best option

Printing lines to the console

Console.WriteLine()

A line break inside a short string

\n

Text or files that should follow the operating system's convention

Environment.NewLine

Formats that require Windows line endings, such as HTTP, SMTP, or some CSV files

\r\n

Building long text from many pieces

StringBuilder.AppendLine()

Inserting variables across several lines

String interpolation with \n or Environment.NewLine

Long blocks of text, JSON, SQL, or HTML in code

Verbatim (@"...") or raw ("""...""") string literals

Putting each item of a collection on its own line

string.Join(Environment.NewLine, items)

Writing lines to a file

File.WriteAllLines() or StreamWriter.WriteLine()

Showing line breaks on a web page

HTML-encode and convert to <br/>, or CSS white-space: pre-line

Key Takeaways

  • \n is the C# new line character, while \r\n is the Windows line ending made of a carriage return and a line feed.
  • Console.WriteLine(), StringBuilder.AppendLine(), and StreamWriter.WriteLine() add a new line for you, using Environment.NewLine.
  • Environment.NewLine returns \r\n on Windows and \n on Linux and macOS, so use it when text should follow the platform's convention.
  • Verbatim and raw string literals let you write multiline strings in C# without any escape characters.
  • Use ReplaceLineEndings() to remove or normalize new lines, and always HTML-encode text before converting new lines to <br/> in ASP.NET.
Wondering how Software Engineers reach senior and leadership roles? Explore the skills, technologies, salary growth, and career progression behind one of the world's most in-demand jobs with this software engineer roadmap.

Conclusion

Adding a C# new line looks simple, but choosing the right method makes your output consistent across platforms, keeps files readable, and keeps web pages safe. For everyday console work, \n and Console.WriteLine() are all you need. For files, longer text, and web output, the other methods in this guide handle the details for you. If you want to build on these skills and develop complete web applications, check out Simplilearn's Full Stack Developer course.

FAQs

1. Why is my \n not showing as a new line on a web page?

Browsers treat line breaks in HTML text as ordinary spaces, so \n won't show up as a new line on its own. Convert line breaks to <br/> tags after HTML-encoding the text, or apply the CSS rule white-space: pre-line to the element that displays it.

2. Does Console.Write add a new line in C#?

No. Console.Write() prints text without a line break, so the next output continues on the same line. Use Console.WriteLine() when you want each piece of output on its own line.

3. How do you add a tab in a C# string?

Use the \t escape sequence, as in "Name\tScore". It's often combined with \n to print simple tables in the console, with \t separating columns and \n separating rows.

4. Can you use Environment.NewLine in a C# const?

No. Environment.NewLine is a property whose value is only known when the program runs, so assigning it to a const causes compiler error CS0133. Use static readonly string instead, or use the "\n" literal if a fixed line ending is acceptable.

5. How do you count the number of lines in a C# string?

Normalize the line endings first and then split the string, as in text.ReplaceLineEndings("\n").Split('\n').Length. This works whether the text uses \n, \r\n, or a mix of both. For files, File.ReadAllLines(path).Length gives you the line count directly.

Our Software Development Program Duration and Fees

Software Development programs typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Full Stack Development Program with Generative AI20 weeks$4,000