How does C# know the length of string using Binary Writer?

Viewed 13

Please look at the code below. This program simply saves a 33-character-length string "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" with an additional byte value of "33".

using System.Text;

namespace Test
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string filepath = args[0];
            using (var stream = File.Open(filepath, FileMode.Create))
            {
                using (var writer = new BinaryWriter(stream, Encoding.UTF8, false))
                {
                    writer.Write(new string('!', 33));
                    writer.Write((byte)33);
                }
            }

            using (var stream = File.Open(filepath, FileMode.Open))
            {
                using (var reader = new BinaryReader(stream, Encoding.UTF8, false))
                {
                    Console.WriteLine(reader.ReadString());
                    Console.WriteLine(reader.ReadByte());
                }
            }

            Console.ReadKey();
        }
    }
}

And here is the binary representation of it:

Binary Representation of Writing Result

Apparently, the first starting "ox21" is the length of the string - but how on earth does C# know?

0 Answers
Related