TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Stream Type

This C# example program uses the Stream type. It casts a derived type to Stream.

Stream. What is a Stream?

In the C# language, you use many different derived streams, such as FileStream and MemoryStream. However, 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 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.

MemoryStreamFile.Open

C# program that uses Stream type

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);
    }
}

Output

5469165
0
1234
0

Avoiding bloat. 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 certain program contexts.

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. This is not important directly.

But: This helps us understand the architecture of Stream types in the .NET Framework.

.NET

Summary. Stream is an abstract base class for more useful streams. It is an implementation of some parts of other streams and a useful way to deal with different streams at a higher level of abstraction. This leads to more compact code.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf