Skip to Main Content
C# in a Nutshell
book

C# in a Nutshell

by Ben Albahari, Ted Neward, Peter Drayton
March 2002
Intermediate to advanced content levelIntermediate to advanced
864 pages
31h 8m
English
O'Reilly Media, Inc.
Content preview from C# in a Nutshell

Encapsulating Raw Streams

While the Stream class reads and writes raw bytes, most programs prefer to produce and consume data either in the form of native data types or lines of text. To make this easy, the framework includes related pairs of XXXReader/XXXWriter classes that provide this higher-level, encapsulated access to the raw underlying data stream.

The BinaryReader and BinaryWriter Classes

BinaryReader and BinaryWriter are concrete classes that define operations for reading and writing a stream of native data types. The most fundamental operations of the BinaryReader and BinaryWriter classes are the methods that read and write instances of the primitive data types: bool, byte, char, decimal, float, double, short, int, long, sbyte, ushort, uint, and ulong. Additionally, methods are provided to read and write strings and arrays of the primitive data types.

Imagine we have a simple class, defined as follows, that we want to read and write from a stream:

public class Student {
  public string Name;
  public int    Age;
  public double GPA;
}

Methods that read and write instances of the Student class from a stream in a binary format might look like this:

void SaveToStream(Stream stm, Student s) { BinaryWriter bw = new BinaryWriter(stm); bw.Write(s.Name); bw.Write(s.Age); bw.Write(s.GPA); bw.Flush(); // Ensure the BinaryWriter buffer is empty } void ReadFromStream(Stream stm, Student s) { BinaryReader br = new BinaryReader(stm); s.Name = br.ReadString(); s.Age = br.ReadInt32(); s.GPA = br.ReadDouble(); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# 8.0 in a Nutshell

C# 8.0 in a Nutshell

Joseph Albahari, Eric Johannsen
C# 10 in a Nutshell

C# 10 in a Nutshell

Joseph Albahari
C# in a Nutshell, Second Edition

C# in a Nutshell, Second Edition

Peter Drayton, Ben Albahari, Ted Neward
Code like a Pro in C#

Code like a Pro in C#

Jort Rodenburg

Publisher Resources

ISBN: 0596001819Catalog PageErrata