# How do C# using and Java try-with-resources map to Rust Drop?
Source: https://ruststudio.org/community/t/53/how-do-c-using-and-java-try-with-resources-map-to-rust-drop
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0, OpenJDK 17.0.18, .NET SDK 10.0.302, Windows 11
Category: Help and questions | Kind: FAQ | Tags: porting, csharp, java | Views: 0

## Short answer
In Rust cleanup is not a statement you must remember. A type that owns a resource implements Drop, and the cleanup runs when the value goes out of scope, in reverse order of creation, on every way out of the function, including early returns and errors. There is no using block and no finalizer.

## Answer
## Answer
In C# you wrap a resource in `using` and in Java in `try (...)`, because the garbage collector will free the memory eventually but will not close the file or the connection at a predictable time. In Rust the owner of a value decides when it dies: at the closing brace of its scope, or earlier if it is moved or passed to `drop`. A type that holds a resource implements the `Drop` trait, and its `drop` method runs at that moment. The standard types you use (`File`, `TcpStream`, `MutexGuard`, `Vec`) already do.

The three programs below do the same thing: open resource `a`, open `b`, then either finish normally or fail. All three were run (the Java and C# listings are excerpts; each program also calls `work` once normally and once failing, and catches the exception); the output is the same order of events.

Java (OpenJDK 17.0.18):

```java
public class Res implements AutoCloseable {
    final String name;
    Res(String n) { name = n; System.out.println("open  " + n); }
    public void close() { System.out.println("close " + name); }

    static void work(boolean fail) throws Exception {
        try (Res a = new Res("a"); Res b = new Res("b")) {
            if (fail) throw new Exception("failed");
            System.out.println("body done");
        }
    }
}
```

C# (.NET SDK 10.0.302):

```csharp
static void Work(bool fail)
{
    using var a = new Res("a");
    using var b = new Res("b");
    if (fail) throw new Exception("failed");
    Console.WriteLine("body done");
}

class Res : IDisposable
{
    readonly string name;
    public Res(string n) { name = n; Console.WriteLine($"open  {n}"); }
    public void Dispose() => Console.WriteLine($"close {name}");
}
```

Rust (rustc 1.93.0), where nothing marks the scope except the variables themselves:

```rust title=src/main.rs
struct Res(&'static str);
impl Res {
    fn open(name: &'static str) -> Res {
        println!("open  {name}");
        Res(name)
    }
}
impl Drop for Res {
    fn drop(&mut self) {
        println!("close {}", self.0);
    }
}

fn work(fail: bool) -> Result<(), String> {
    let _a = Res::open("a");
    let _b = Res::open("b");
    if fail {
        return Err("failed".into());
    }
    println!("body done");
    Ok(())
}

fn main() {
    println!("-- normal");
    work(false).unwrap();
    println!("-- early return");
    let _ = work(true);
    println!("-- moved value is closed by its new owner");
    let r = Res::open("c");
    let keeper = vec![r];
    println!("moved into a Vec");
    drop(keeper);
    println!("end");
}
```

```text
-- normal
open  a
open  b
body done
close b
close a
-- early return
open  a
open  b
close b
close a
-- moved value is closed by its new owner
open  c
moved into a Vec
close c
end
```

The Java run and the C# run printed the same sequence for the normal and failing cases (`open a`, `open b`, `body done` or the failure, `close b`, `close a`); Java and C# then printed the caught exception message `failed`. In Rust a failure is a `Result`, so the early return is a normal `return`, and the `close` lines come out in the same order. The last case has no equivalent in `using`: a value that is moved into a `Vec` is closed when the `Vec` is dropped, because that is its new owner.

## How to do it
1. For each class that implements `IDisposable` or `AutoCloseable`, make a struct that owns the resource and implement `Drop`. If the resource is already a Rust type (a `File`), you need no wrapper.
2. Delete the `using` and `try` blocks. Make sure each resource variable lives as long as it needs to, and no longer: control the lifetime with blocks (`{ let f = File::open(..)?; ... }`) or `drop(x)`.
3. Keep `drop` simple and infallible. If closing can fail and you must know, add an explicit method (`close(self) -> Result<..>`) and call it where you can report the error; `drop` cannot return one.
4. For resources owned by C code, wrap the handle in a struct and call the C `free` or `close` in `Drop` (see the thread on calling a C library).

## Common mistakes
- Using `let _ = Res::open("a");` and expecting the resource to live on. A binding named `_` drops the value at once; name it `_a` to keep it until the end of the scope.
- Relying on `drop` for something that must happen even if the process aborts or is killed. Destructors do not run in that case.
- Putting slow or blocking work in `drop` of something that is dropped inside a lock or a hot loop.

## Related questions
### Is `Drop` the same as a C# finalizer?
No. A finalizer runs at a time the garbage collector chooses, perhaps never. `Drop` runs at a fixed point in the program, every time.

### What happens if the code panics?
By default the stack unwinds and values still in scope are dropped on the way, so resources are released. A program built with `panic = "abort"` does not unwind.

## Sources
- The Rust Book, "Running Code on Cleanup with the Drop Trait": https://doc.rust-lang.org/book/ch15-03-drop.html
- `std::ops::Drop`: https://doc.rust-lang.org/std/ops/trait.Drop.html
