
You want to convert your string into a byte array, using the C# language. Because strings in the C# language are stored with two bytes per character, and ASCII only allows one byte per character, this can cause data loss if the string is not actually ASCII-encoded. The Encoding.ASCII.GetBytes method is demonstrated here.
First off, we look at a program that uses a constant string literal and then converts that to a byte array. Please note that the GetBytes method will cause an incorrect conversion if the input string is not actually ASCII. In the final loop, we examine each byte of the resulting byte array and see its numeric and also character-based representation; this demonstrates correctness.
This C# program converts a string to a byte array. It uses Encoding.ASCII.GetBytes.
Program that uses Encoding.ASCII.GetBytes method [C#]
using System;
using System.Text;
class Program
{
static void Main()
{
// Input string.
const string input = "Dot Net Perls";
// Invoke GetBytes method.
// ... You can store this array as a field!
byte[] array = Encoding.ASCII.GetBytes(input);
// Loop through contents of the array.
foreach (byte element in array)
{
Console.WriteLine("{0} = {1}", element, (char)element);
}
}
}
Output
68 = D
111 = o
116 = t
32 =
78 = N
101 = e
116 = t
32 =
80 = P
101 = e
114 = r
108 = l
115 = sExamining the output. The character representations from the input string were first converted to fit in one byte elements each. Then, we see that the integer 68 corresponds to the uppercase letter 'D'; this is the standard.

How can you use the Encoding.ASCII.GetBytes method to optimize the memory usage in your C# program? Let's say you have some string caches in your program and these must be resident in memory for some time. Instead of leaving them as strings, you can convert them to byte[] arrays (if they are ASCII). This will occupy half the memory; also, the reduction in memory usage will possibly improve performance of garbage collection and decrease its frequency, by improving memory locality.

It is possible to easily convert strings into byte arrays using the C# programming language. Please note that this conversion may cause some data loss if you are using some characters that are not in the ASCII character set. Because of this, be careful when using this method in places where not absolutely necessary.
Convert Byte Array to String Cast Examples