Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Environment.NewLine in C#
The Environment.NewLine property in C# provides a platform-independent way to add line breaks in strings. It automatically returns the appropriate newline character sequence for the current operating system − \r on Windows and on Unix-based systems.
Using Environment.NewLine ensures your code works correctly across different platforms without hardcoding specific line break characters.
Syntax
Following is the syntax for using Environment.NewLine −
string result = text1 + Environment.NewLine + text2;
You can also use it in string concatenation or interpolation −
string result = $"Line 1{Environment.NewLine}Line 2";
Basic Usage Example
Here's how to use Environment.NewLine to create multi-line strings −
using System;
class Program {
static void Main(string[] args) {
string str = "This is demo text!" + Environment.NewLine + "This is demo text on next line!";
Console.Write(str);
}
}
The output of the above code is −
This is demo text! This is demo text on next line!
Using Environment.NewLine in String Interpolation
using System;
class Program {
static void Main(string[] args) {
string name = "John";
int age = 25;
string message = $"Name: {name}{Environment.NewLine}Age: {age}{Environment.NewLine}Status: Active";
Console.WriteLine(message);
}
}
The output of the above code is −
Name: John Age: 25 Status: Active
Multiple Line Breaks
You can add multiple line breaks by concatenating Environment.NewLine multiple times −
using System;
class Program {
static void Main(string[] args) {
string header = "REPORT HEADER";
string content = "Report data here";
string footer = "End of Report";
string report = header + Environment.NewLine + Environment.NewLine +
content + Environment.NewLine + Environment.NewLine +
footer;
Console.WriteLine(report);
}
}
The output of the above code is −
REPORT HEADER Report data here End of Report
Comparison with Other Line Break Methods
| Method | Cross-Platform | Description |
|---|---|---|
Environment.NewLine |
Yes | Platform-specific newline sequence |
" |
Limited | Unix/Linux newline (may not work on Windows) |
"\r |
Limited | Windows newline (may not work on Unix systems) |
Conclusion
Environment.NewLine provides a reliable, cross-platform way to add line breaks in C# applications. It automatically uses the correct newline sequence for the current operating system, making your code more portable and maintainable across different platforms.
