Name:
Location: Rowland Heights, California, United States

Thursday, March 31, 2005

C# New Line Carriage Return

You ever wonder why the .NET Development Team didn't just put the escape sequence characters into Constants? Well they did... Sort of!

Here are two samples of code that do the same thing:

// First Sample
StringBuilder sb = new StringBuilder();
sb.Add("This the first line,");
sb.Add("/r/n");
sb.Add("Here is the second line.");

// Second Sample
StringBuilder sb = new StringBuilder();
sb.Add("This the first line,");
sb.Add(System.Environment.NewLine);
sb.Add("Here is the second line.");

Notice how instead of using the escape sequence characters in the second example I used a built Constant that the .NET Team Provided for you and I. This method is so much cleaner and so much more understandable. This works great when you're working with someone that is new to the .NET Framework.

You should also check out what else they have the System.Environment Class.

Here's a link where you can get more escape sequence characters.

4 Comments:

Blogger Chris Burkhardt said...

Sorry bro, the code is:

StringBuilder sb = new StringBuilder();
sb.Append("first line in default");
sb.Append("\r\n");
sb.Append("Second line in default");

Sring builder uses append, not add. C# escape char is "\" not "/, and no space between \r and \n if you want it to work with notepad.

2:45 PM  
Blogger JAG_KILROY said...

Just wanted to say thanks for having some of the simple questions answered here.

Walter

6:10 AM  
Blogger Dave Schinkel said...

don't forget AppendLine("
"); for the web instead of \r\n

1:02 PM  
Blogger Unknown said...

Oh sweet-- thanks for the tip! I used System.Environment.NewLine last night!

5:56 AM  

Post a Comment

<< Home