Home
C#
Stream
This page was last reviewed on Jul 31, 2021.
Dot Net Perls
Stream. We use many different derived streams, such as FileStream and MemoryStream. A single C# program often uses many streams together.
MemoryStream
FileStream
Direct use. In most programs, the Stream type itself isn't usually used directly. It instead is an abstract base class for more derived streams.
Example. Because Stream is an abstract base class for other streams such as FileStream and MemoryStream, you can implicitly cast those streams to Stream types.
Here We introduce a method (the static Print method) that receives a Stream formal parameter.
Note You can pass instances of FileStream and MemoryStream to this method. We use the Stream abstraction to perform certain tasks.
File.Open
using System; using System.IO; class Program { static void Main() { FileStream stream1 = File.Open("C:\\a", FileMode.Open); Print(stream1); MemoryStream stream2 = new MemoryStream(new byte[1234]); Print(stream2); } static void Print(Stream stream) { Console.WriteLine(stream.Length); Console.WriteLine(stream.Position); } }
5469165 0 1234 0
Because Stream can substitute for many different derived streams, it is sometimes useful to have a field or parameter of type Stream. This can help in some methods.
Tip This means you can avoid having duplicate methods (such as one that receives FileStream and one that receives MemoryStream).
Implementation. The Stream class is an abstract class containing many abstract and virtual methods. These methods are implemented in the classes that inherit from Stream.
Info This helps us understand the architecture of Stream types in the .NET Framework.
Summary. Stream is an abstract base class for more useful streams. It is a useful way to deal with different streams at a higher level of abstraction.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jul 31, 2021 (rewrite).
Home
Changes
© 2007-2024 Sam Allen.