Recall & Review
beginner
What is the purpose of the
using statement when working with file streams in C#?The
using statement ensures that the file stream is automatically closed and disposed of properly after its use, even if an error occurs. This helps prevent resource leaks.Click to reveal answer
beginner
How does the
using statement improve code safety when handling files?It automatically calls
Dispose() on the file stream object at the end of the block, which closes the file and frees resources, reducing the chance of file locks or memory leaks.Click to reveal answer
beginner
Show a simple example of using the
using statement to read text from a file.using (var reader = new StreamReader("file.txt"))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
Click to reveal answer
intermediate
What happens if an exception occurs inside a
using block with a file stream?Even if an exception happens, the
using statement ensures the file stream's Dispose() method is called, so the file is properly closed and resources are released.Click to reveal answer
intermediate
Can you use multiple file streams in a single
using statement? How?Yes, you can declare multiple streams separated by commas inside one
using statement, like:<br>using (var fs1 = new FileStream(...), fs2 = new FileStream(...)) { ... }Click to reveal answer
What does the
using statement do with a file stream in C#?✗ Incorrect
The
using statement ensures the file stream is closed and disposed automatically after the block finishes.Which method is called automatically at the end of a
using block for a file stream?✗ Incorrect
Dispose() is called automatically to release resources, which also closes the file stream.
What happens if an exception occurs inside a
using block?✗ Incorrect
Dispose() is called even if an exception occurs, ensuring the file stream is closed properly.
How can you declare multiple file streams in one
using statement?✗ Incorrect
Multiple streams can be declared separated by commas inside a single
using statement.Why is it better to use
using instead of manually calling Close() on a file stream?✗ Incorrect
using ensures proper cleanup even if exceptions occur, making code safer and cleaner.Explain how the
using statement helps manage file streams in C#.Think about what happens to the file stream after the block finishes.
You got /4 concepts.
Write a short code example using the
using statement to read all text from a file and print it.Use StreamReader inside a using block and read the file content.
You got /4 concepts.