OnSwipe redirect code

Tuesday, March 4, 2008

Special chars and Escape sequences in .NET strings

Having come from C/C++ programming, and that too mainly console programming, escape sequences were very dear to me as they were my sole friends when it came to formatting the output. Now at work I work with C# .NET and things are not the same. I wrote a XSLT processor, as part of my job, and I wanted to log every successful XSL trasnformation. Well the file I/O was a lot easier with .NET types, but introducing an newline at the end of every log entry was a big pain. As I used to do earlier I simple put a "\n" at the end of the log message. This resulted in a empty square box being placed there instead of a newline. This was totally wierd and I started to wonder whether I have been writing Japanese???!!!

Then a little bit googling told me that .NET has encapsulated these special chars and newlines in a type called "Environment". This makes sense. Newline can be differnet in different environment. And with this encapsulation we get the correct newline for any environment.

So in C# if you want to add a newline to your string use the "Environment.Newline" object. VB .NET developers are, as usual, lucky with a easier encapsulation. They have a type called "ControlChars" and this can be used like this: "ControlChars.crlf" which of course is more intutive that something like environment.

2 comments:

  1. I thought \n works in C#. I am not sure of writing to a file, but sure on the console.

    ReplyDelete
  2. Prajeesh,

    From what I know, culture and environment will not have any impact when putting it to console. But when writing to file, all that along with encoding and all that will come into effect. And that is why encapsulating it into a type makes sense.

    ReplyDelete