Freigeben über


SYSK 280: ControlChars in C# Without Using Microsoft.VisualBasic Assembly

Microsoft.VisualBasic namespace has a handy class, ControlChars, with the following public fields: Back, Cr, CrLf, FormFeed, Lf, NewLine, NullChar, Quote, Tab, VerticalTab. After seeing some C# developers use it just for the simplicity of code like this:

string[] data = myString.Split(ControlChars.NewLine);

I decided to blog on this topic…

 

First, if all you need is to get an array of substring from a source string separated by a new line (carriage return + line feed) delimiter, you can use the following code in C#:

string[] lines = myString.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

 

If you like the idea of using ControlChars class, you can create your own, so you don’t take on the overhead of loading another assembly just for one class:

 

public class ControlChars

{

    public const string CrLf = "\r\n";

    public const string NewLine = "\r\n";

    public const char Cr = (char)13;

    public const char Lf = (char)10;

    public const char Back = (char)8;

    public const char FormFeed = (char)12;

    public const char Tab = (char)9;

    public const char VerticalTab = (char)11;

    public const char NullChar = (char)0;

    public const char Quote = (char)34;

}

Comments

  • Anonymous
    February 05, 2007
    Shouldn't you define the NewLine const according to Enviornment.NewLine??

  • Anonymous
    February 05, 2007
    Interesting observation...  Environment.NewLine will result in "rn" for non-Unix platforms, and "n" for Unix platforms.  So, if you're writing for platforms other than Windows, David's suggestion is right on!  You won't be able to keep the 'const' modifyer, but that's Ok...

  • Anonymous
    February 13, 2007
    You could use 'readonly' instead of 'const' in David's case however, which would amount to the same thing anyway. The difference being that it's actually initialized at run time and not at compile time.

  • Anonymous
    April 10, 2007
    THANK YOU SO MUCH I Searched for this for hours..

  • Anonymous
    July 01, 2008
    FYI, using .NET Reflector we see that Microsoft doesn't use Environment.NewLine, so if you want to exactly match the VB implementation, here it is: public sealed class ControlChars {    // Fields    public const char Back = 'b';    public const char Cr = 'r';    public const string CrLf = "rn";    public const char FormFeed = 'f';    public const char Lf = 'n';    public const string NewLine = "rn";    public const char NullChar = '�';    public const char Quote = '"';    public const char Tab = 't';    public const char VerticalTab = 'v'; }