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;

}