Bird
Raised Fist0
C Sharp (C#)programming~20 mins

Using statement for resource cleanup in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Using Statement Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this C# code using the 'using' statement?

Consider the following code snippet:

using System;
class Resource : IDisposable {
    public void Dispose() {
        Console.WriteLine("Resource disposed");
    }
    public void Use() {
        Console.WriteLine("Resource in use");
    }
}

class Program {
    static void Main() {
        using (var r = new Resource()) {
            r.Use();
        }
        Console.WriteLine("End of Main");
    }
}

What will be printed when this program runs?

C Sharp (C#)
using System;
class Resource : IDisposable {
    public void Dispose() {
        Console.WriteLine("Resource disposed");
    }
    public void Use() {
        Console.WriteLine("Resource in use");
    }
}

class Program {
    static void Main() {
        using (var r = new Resource()) {
            r.Use();
        }
        Console.WriteLine("End of Main");
    }
}
A
Resource in use
Resource disposed
End of Main
B
Resource disposed
Resource in use
End of Main
C
Resource in use
End of Main
Resource disposed
D
End of Main
Resource in use
Resource disposed
Attempts:
2 left
💡 Hint

Think about when the Dispose method is called in a 'using' block.

Predict Output
intermediate
2:00remaining
What happens if an exception occurs inside a 'using' block?

Look at this code:

using System;
class Resource : IDisposable {
    public void Dispose() {
        Console.WriteLine("Disposed");
    }
    public void Use() {
        Console.WriteLine("Using resource");
        throw new Exception("Error");
    }
}

class Program {
    static void Main() {
        try {
            using (var r = new Resource()) {
                r.Use();
            }
        } catch (Exception e) {
            Console.WriteLine(e.Message);
        }
    }
}

What will be the output when this runs?

C Sharp (C#)
using System;
class Resource : IDisposable {
    public void Dispose() {
        Console.WriteLine("Disposed");
    }
    public void Use() {
        Console.WriteLine("Using resource");
        throw new Exception("Error");
    }
}

class Program {
    static void Main() {
        try {
            using (var r = new Resource()) {
                r.Use();
            }
        } catch (Exception e) {
            Console.WriteLine(e.Message);
        }
    }
}
A
Error
Using resource
Disposed
B
Disposed
Using resource
Error
C
Using resource
Disposed
Error
D
Using resource
Error
Disposed
Attempts:
2 left
💡 Hint

Dispose is called even if an exception happens inside the 'using' block.

🔧 Debug
advanced
2:00remaining
Why does this code cause a compile error related to 'using'?

Examine this code snippet:

using System;
class Program {
    static void Main() {
        using var r = new Resource();
        r.Use();
    }
}

class Resource {
    public void Use() {
        Console.WriteLine("Using resource");
    }
}

Why does this code fail to compile?

C Sharp (C#)
using System;
class Program {
    static void Main() {
        using var r = new Resource();
        r.Use();
    }
}

class Resource {
    public void Use() {
        Console.WriteLine("Using resource");
    }
}
AResource does not implement IDisposable, so 'using var' is invalid
BThe 'using var' syntax requires parentheses around the variable declaration
CThe 'using' statement cannot be used with local variables
DThe 'Use' method must be called inside a 'using' block, not after
Attempts:
2 left
💡 Hint

Check if the resource type supports disposal.

📝 Syntax
advanced
2:00remaining
Which option correctly uses the 'using' statement with multiple resources?

Choose the correct syntax to use two disposable resources in a single 'using' statement.

Ausing var r1 = new Resource1(); using var r2 = new Resource2(); /* code */
Busing (var r1 = new Resource1(), r2 = new Resource2()) { /* code */ }
Cusing (var r1 = new Resource1()) using (var r2 = new Resource2()) { /* code */ }
Dusing (var r1 = new Resource1(); var r2 = new Resource2()) { /* code */ }
Attempts:
2 left
💡 Hint

Look for comma-separated declarations inside the using parentheses.

🚀 Application
expert
3:00remaining
What is the final value of 'count' after this code runs?

Analyze this code:

using System;
class Counter : IDisposable {
    public static int count = 0;
    public Counter() {
        count++;
    }
    public void Dispose() {
        count--;
    }
}

class Program {
    static void Main() {
        using (var c1 = new Counter()) {
            using (var c2 = new Counter()) {
                // do nothing
            }
            using (var c3 = new Counter()) {
                // do nothing
            }
        }
        Console.WriteLine(Counter.count);
    }
}

What is printed?

C Sharp (C#)
using System;
class Counter : IDisposable {
    public static int count = 0;
    public Counter() {
        count++;
    }
    public void Dispose() {
        count--;
    }
}

class Program {
    static void Main() {
        using (var c1 = new Counter()) {
            using (var c2 = new Counter()) {
                // do nothing
            }
            using (var c3 = new Counter()) {
                // do nothing
            }
        }
        Console.WriteLine(Counter.count);
    }
}
A3
B1
C2
D0
Attempts:
2 left
💡 Hint

Think about when Dispose is called and how it affects the static count.

Practice

(1/5)
1. What is the main purpose of the using statement in C#?
easy
A. To automatically release resources when the block is done
B. To declare a variable that cannot be changed
C. To create a new thread for parallel execution
D. To handle exceptions thrown inside the block

Solution

  1. Step 1: Understand the role of using

    The using statement is designed to ensure that resources like files or database connections are properly closed or disposed after use.
  2. Step 2: Compare with other options

    Options A, C, and D describe other concepts: immutability, threading, and exception handling, which are unrelated to using.
  3. Final Answer:

    To automatically release resources when the block is done -> Option A
  4. Quick Check:

    Using statement = automatic resource cleanup [OK]
Hint: Using means auto-cleanup of resources after use [OK]
Common Mistakes:
  • Thinking using declares constants
  • Confusing using with try-catch
  • Assuming using creates threads
2. Which of the following is the correct syntax for a using statement in C#?
easy
A. using (var file = new FileStream("file.txt", FileMode.Open)) { /* code */ }
B. using var file = new FileStream("file.txt", FileMode.Open); { /* code */ }
C. using var file = new FileStream("file.txt", FileMode.Open) { /* code */ }
D. using (var file = new FileStream("file.txt", FileMode.Open)); { /* code */ }

Solution

  1. Step 1: Identify correct using block syntax

    The correct syntax uses parentheses around the resource declaration and a block with braces: using (var resource = ... ) { ... }.
  2. Step 2: Check each option

    using (var file = new FileStream("file.txt", FileMode.Open)) { /* code */ } matches the correct syntax. using var file = new FileStream("file.txt", FileMode.Open); { /* code */ } misses parentheses and incorrectly uses a semicolon. using var file = new FileStream("file.txt", FileMode.Open) { /* code */ } misses parentheses and braces. using (var file = new FileStream("file.txt", FileMode.Open)); { /* code */ } has a semicolon after the parentheses, which is invalid.
  3. Final Answer:

    using (var file = new FileStream("file.txt", FileMode.Open)) { /* code */ } -> Option A
  4. Quick Check:

    Using syntax = parentheses + braces [OK]
Hint: Using needs parentheses and braces for the resource block [OK]
Common Mistakes:
  • Omitting parentheses around resource
  • Adding semicolon after using parentheses
  • Missing braces for the code block
3. What will be the output of this code snippet?
using (var writer = new System.IO.StreamWriter("test.txt"))
{
    writer.WriteLine("Hello");
}
Console.WriteLine("Done");
medium
A. Hello
B. Compilation error
C. Hello\nDone
D. Done

Solution

  1. Step 1: Understand the using block behavior

    The using block writes "Hello" to the file "test.txt" and disposes the writer after the block ends. It does not print anything to the console.
  2. Step 2: Check the console output

    The only console output is from Console.WriteLine("Done"), so the output is "Done".
  3. Final Answer:

    Done -> Option D
  4. Quick Check:

    Using writes file, console prints "Done" [OK]
Hint: Using writes files, only Console.WriteLine prints output [OK]
Common Mistakes:
  • Expecting file content to print on console
  • Confusing file write with console output
  • Thinking using prints automatically
4. Identify the error in this code snippet:
using (var stream = new FileStream("data.txt", FileMode.Open))
stream.ReadByte();
Console.WriteLine("Read complete");
medium
A. ReadByte() is not a valid method
B. Missing braces {} around the using block
C. FileStream does not implement IDisposable
D. Console.WriteLine should be inside the using block

Solution

  1. Step 1: Check using block syntax

    The using statement requires braces {} if the block contains more than one statement or to clearly define the scope.
  2. Step 2: Analyze the code structure

    Here, the using statement lacks braces, so only the next statement is inside the block. The Console.WriteLine is outside but indentation suggests otherwise. This is a syntax error or at least a logic error.
  3. Final Answer:

    Missing braces {} around the using block -> Option B
  4. Quick Check:

    Using needs braces for multiple statements [OK]
Hint: Always use braces {} with using for multiple statements [OK]
Common Mistakes:
  • Assuming using works without braces for multiple lines
  • Thinking FileStream is not IDisposable
  • Confusing method names
5. You want to open two files and write "Start" to the first and "End" to the second, ensuring both files are properly closed after writing. Which code correctly uses nested using statements for this?
hard
A. using (var file1 = new StreamWriter("start.txt")) { file1.WriteLine("Start"); } using (var file2 = new StreamWriter("end.txt")) { file2.WriteLine("End"); }
B. using (var file1 = new StreamWriter("start.txt")) using (var file2 = new StreamWriter("end.txt")) { file1.WriteLine("Start"); file2.WriteLine("End"); }
C. using (var file1 = new StreamWriter("start.txt")) { using (var file2 = new StreamWriter("end.txt")) { file1.WriteLine("Start"); file2.WriteLine("End"); } }
D. using var file1 = new StreamWriter("start.txt"); using var file2 = new StreamWriter("end.txt"); file1.WriteLine("Start"); file2.WriteLine("End");

Solution

  1. Step 1: Understand nested using statements

    Nested using statements place one using inside the block of another: using (var outer = ...) { using (var inner = ...) { /* use both */ } }. This ensures both resources are disposed, inner first.
  2. Step 2: Compare options

    using (var file1 ...) { file1... } using (var file2 ...) { file2... } uses sequential, not nested. using (var file1...) using (var file2...) { ... } lacks braces for first using, invalid syntax. using var file1...; using var file2...; ... uses declarations (C# 8+), not statements. Only using (var file1 ...) { using (var file2 ...) { ... } } is nested using statements.
  3. Final Answer:

    using (var file1 = new StreamWriter("start.txt")) { using (var file2 = new StreamWriter("end.txt")) { file1.WriteLine("Start"); file2.WriteLine("End"); } } -> Option C
  4. Quick Check:

    Nested using = using block inside using block [OK]
Hint: Nested using: outer { inner using } for multiple resources [OK]
Common Mistakes:
  • Omitting braces in nested using
  • Confusing nested and sequential using
  • Misusing using var without braces