Difference between “\n” and Environment.NewLine

2019-01-02 18:05发布

What is the difference between two, if any (with respect to .Net)?

7条回答
高级女魔头
2楼-- · 2019-01-02 18:15

Depends on the platform. On Windows it is actually "\r\n".

From MSDN:

A string containing "\r\n" for non-Unix platforms, or a string containing "\n" for Unix platforms.

查看更多
梦醉为红颜
3楼-- · 2019-01-02 18:17

Environment.NewLine will return the newline character for the corresponding platform in which your code is running

you will find this very useful when you deploy your code in linux on the Mono framework

查看更多
倾城一夜雪
4楼-- · 2019-01-02 18:17

From the docs ...

A string containing "\r\n" for non-Unix platforms, or a string containing "\n" for Unix platforms.

查看更多
春风洒进眼中
5楼-- · 2019-01-02 18:18

Environment.NewLine will give "\r\n" when run on Windows. If you are generating strings for Unix based environments, you don't want the "\r".

查看更多
人气声优
6楼-- · 2019-01-02 18:23

Exact implementation of Environment.NewLine from the source code:

The implementation in .NET 4.6.1:

/*===================================NewLine====================================
**Action: A property which returns the appropriate newline string for the given
**        platform.
**Returns: \r\n on Win32.
**Arguments: None.
**Exceptions: None.
==============================================================================*/
public static String NewLine {
    get {
        Contract.Ensures(Contract.Result<String>() != null);
        return "\r\n";
    }
}

source


The implementation in .NET Core:

/*===================================NewLine====================================
**Action: A property which returns the appropriate newline string for the
**        given platform.
**Returns: \r\n on Win32.
**Arguments: None.
**Exceptions: None.
==============================================================================*/
public static String NewLine {
    get {
        Contract.Ensures(Contract.Result() != null);
#if !PLATFORM_UNIX
        return "\r\n";
#else
        return "\n";
#endif // !PLATFORM_UNIX
    }
}

source (in System.Private.CoreLib)

public static string NewLine => "\r\n";

source (in System.Runtime.Extensions)

查看更多
人气声优
7楼-- · 2019-01-02 18:33

You might get into trouble when you try to display multi-line message separated with "\r\n".

It is always a good practice to do things in a standard way, and use Environment.NewLine

查看更多
登录 后发表回答