Allen Jones


Manipulate the Contents of a String Efficiently

Problem: You need to manipulate the contents of a String object and want to avoid the overhead of automatic String creation caused by the immutability of String objects.

Solution: Use the System.Text.StringBuilder class to perform the manipulations and convert the result to a String using the StringBuilder.ToString method.


Encode a String Using Alternate Character Encoding

Problem: You need to exchange character data with systems that use character encoding schemes other than UTF-16—the character-encoding scheme used internally by the CLR.

Solution: Use the System.Text.Encoding class and its subclasses to convert characters between different encoding schemes.


Convert Basic Value Types to Byte Arrays

Problem: You need to convert basic value types to byte arrays.

Solution: The static methods of the System.BitConverter class provide a convenient mechanism through which to convert most basic value types except the decimal type to and from byte arrays. To convert a decimal to a byte array, write the decimal to a System.IO.MemoryStream instance using a System.IO.BinaryWriter object and then call the MemoryStream.ToArray method. To create a decimal from a byte array, create a MemoryStream object from the byte array and read the decimal from the MemoryStream using a System.IO.BinaryReader instance.


Encode Binary Data as Text

Problem: You need to convert binary data into a form that can be stored as part of an ASCII text file (such as an XML file), or sent as part of an e-mail message.

Solution: Use the static methods ToBase64String and FromBase64String of the System.Convert class to convert your binary data to and from a Base64-encoded string.


Validate Input Using Regular Expressions

Problem: You need to validate that user input or data read from a file has the expected structure and content. For example, you want to ensure that a user enters a valid IP address, telephone number, or e-mail address.

Solution: Use regular expressions to ensure that the input data follows the correct structure and contains only valid characters for the expected type of information.


Create Dates and Times from Strings

Problem: You need to create a System.DateTime instance that represents the time and date specified in a string.

Solution: Use the Parse or ParseExact methods of the DateTime class.