Search code examples
javac#using-statementtry-with-resources

Difference between .NETs using-Statement and Javas try-with-ressources


I learned C# in school and now I started to learn Java.

In Java there is "try with ressources" which will close/dispose stuff (like a Scanner) when it's not used anymore.

The equivalent C# is the using-Statement, which basically does the same.

Are they really exactly the same, or are there any differences (like what they are doing in background)?


Solution

  • No, they're not exactly the same.

    • try-with-resources statements can declare multiple variables of different types; using statements can declare multiple variables, but they all have to be of the same type
    • A using statement doesn't have to declare any variables; using (foo) is fine - whereas a try-with-resources statement
    • A variable declared in a using statement is still assignable, although it's still the initial value which is disposed, rather than the value at the end of the block; a variable declared in a try-with-resources statement cannot be assigned within the block
    • A try-with-resources statement can have catch and finally blocks, whereas you'd need to have a separate try/catch or try/catch/finally block in C#
    • If the body of a using statement throws an exception, and then the Dispose method throws an exception, then only the latter exception is available; in try-with-resources the exceptions from closing are "suppressed" (so the statement result is the exception from the try block) but the closing exceptions can still be retrieved using Throwable.getSuppressed.