What are streams in C#?
๐ก Concept: Streams in C#
Streams are abstract representations of sequences of bytes used for reading and writing data sequentially.
๐ Quick Intro
Streams provide a uniform way to handle data input and output from different sources like files, memory, and network connections.
๐ง Analogy
Think of streams as a conveyor belt moving data one piece at a time between producer and consumer.
๐ง Technical Explanation
- ๐ Streams support sequential read/write operations.
- ๐ Types include FileStream, MemoryStream, NetworkStream, etc.
- โ๏ธ Streams can be synchronous or asynchronous.
- ๐ ๏ธ Properly closing streams is essential to release resources.
- ๐ Streams implement IDisposable for cleanup.
๐ฏ Use Cases
- โ Reading and writing files.
- โ Handling network data.
- โ Memory manipulation.
- โ Data compression and encryption streams.
๐ป Code Example
using System;
using System.IO;
class Program {
static void Main() {
using (FileStream fs = new FileStream(""example.txt"", FileMode.OpenOrCreate)) {
byte[] info = new byte[] { 1, 2, 3, 4, 5 };
fs.Write(info, 0, info.Length);
fs.Seek(0, SeekOrigin.Begin);
byte[] buffer = new byte[info.Length];
fs.Read(buffer, 0, buffer.Length);
Console.WriteLine(string.Join("","", buffer));
}
}
}

โ Interview Q&A
Q1: What is a stream?
A: An abstraction for reading/writing sequential data.
Q2: Name some stream types.
A: FileStream, MemoryStream, NetworkStream.
Q3: Why close streams?
A: To release resources and avoid leaks.
Q4: Can streams be asynchronous?
A: Yes.
Q5: What interface do streams implement?
A: IDisposable.
Q6: How to read from a stream?
A: Using Read or ReadAsync methods.
Q7: How to write to a stream?
A: Using Write or WriteAsync methods.
Q8: Can streams be used for networking?
A: Yes, NetworkStream is designed for this.
Q9: Are streams buffered?
A: Often, to improve performance.
Q10: What is FileMode?
A: Enum for file open modes.
๐ MCQs
Q1. What is a stream?
- Thread
- Stream
- Task
- Process
Q2. Name some stream types.
- Thread, Task
- FileStream, MemoryStream
- Socket, Process
- File, Directory
Q3. Why close streams?
- No reason
- Release resources
- Avoid bugs
- Increase speed
Q4. Can streams be asynchronous?
- No
- Yes
- Sometimes
- Never
Q5. What interface do streams implement?
- IEnumerable
- IDisposable
- IComparable
- ICloneable
Q6. How to read from a stream?
- Write
- Close
- Read or ReadAsync
- Flush
Q7. How to write to a stream?
- Read
- Write or WriteAsync
- Close
- Flush
Q8. Can streams be used for networking?
- No
- Yes
- Sometimes
- Never
Q9. Are streams buffered?
- Never
- Often
- Sometimes
- Always
Q10. What is FileMode?
- FileMode
- FileAccess
- FileShare
- FileOptions
๐ก Bonus Insight
Streams provide a flexible and efficient way to handle I/O across various sources in C#.
๐ PDF Download
Need a handy summary for your notes? Download this topic as a PDF!