Skip to Main Content
C# in a Nutshell, Second Edition
book

C# in a Nutshell, Second Edition

by Peter Drayton, Ben Albahari, Ted Neward
August 2003
Intermediate to advanced content levelIntermediate to advanced
928 pages
32h 1m
English
O'Reilly Media, Inc.
Content preview from C# in a Nutshell, Second Edition

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 ...
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# in a Nutshell

C# in a Nutshell

Ben Albahari, Ted Neward, Peter Drayton
C# 7.0 in a Nutshell

C# 7.0 in a Nutshell

Joseph Albahari, Ben Albahari
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
C# Cookbook

C# Cookbook

Joe Mayo

Publisher Resources

ISBN: 0596005261Catalog PageErrata