User kokos answered the wonderful Hidden Features of C# question by mentioning the using
keyword. Can you elaborate on that? What are the uses of
In conclusion, when you use a local variable of a type that implements IDisposable
, always, without exception, use using
1.
If you use nonlocal IDisposable
variables, then always implement the IDisposable pattern.
Two simple rules, no exception1. Preventing resource leaks otherwise is a real pain in the *ss.
1): The only exception is – when you're handling exceptions. It might then be less code to call Dispose
explicitly in the finally
block.
The using statement tells .NET to release the object specified in the using block once it is no longer needed. So you should use 'using' block for classes that require cleaning up after them, like System.IO Types.
The using statement provides a convenience mechanism to correctly use IDisposable objects. As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.
This comes from: here
When using ADO.NET you can use the keywork for things like your connection object or reader object. That way when the code block completes it will automatically dispose of your connection.
For me the name "using" is a little bit confusing, because is can be a directive to import a Namespace or a statement (like the one discussed here) for error handling.
A different name for error handling would've been nice, and maybe a somehow more obvious one.