Recall & Review
beginner
What is the purpose of the
using statement in C#?The
using statement ensures that an object that uses unmanaged resources is properly disposed of when it is no longer needed, helping to clean up resources automatically.Click to reveal answer
beginner
How does the
using statement help with resource cleanup?It automatically calls the
Dispose() method on the object at the end of the using block, even if an exception occurs inside the block.Click to reveal answer
beginner
Which interface must an object implement to be used in a
using statement?The object must implement the
IDisposable interface to be used in a using statement.Click to reveal answer
intermediate
What happens if an exception is thrown inside a
using block?The
Dispose() method is still called to clean up the resource before the exception propagates, ensuring no resource leaks.Click to reveal answer
beginner
Show a simple example of a
using statement with a file stream.Example:<br>
using (var file = new System.IO.StreamWriter("file.txt"))
{
file.WriteLine("Hello, world!");
}<br>This writes to the file and automatically closes it after the block.Click to reveal answer
What does the
using statement guarantee in C#?✗ Incorrect
The
using statement guarantees the resource's Dispose() method is called after the block finishes.Which interface must an object implement to be used in a
using statement?✗ Incorrect
Only objects implementing
IDisposable can be used in a using statement.What happens if an exception occurs inside a
using block?✗ Incorrect
The
Dispose() method is called even if an exception occurs, ensuring cleanup.Which of these is a correct use of the
using statement?✗ Incorrect
Both the traditional block form and the newer C# 8.0+ using declaration are valid.
Why is the
using statement preferred over manual Dispose() calls?✗ Incorrect
The
using statement ensures disposal happens reliably, even with exceptions.Explain how the
using statement helps manage resources in C#.Think about what happens when the code inside the block finishes or throws an error.
You got /4 concepts.
Write a simple example using the
using statement to open and write to a file.Use the <code>using</code> block to create a file writer and write a line.
You got /4 concepts.