Tutorial by Examples

using is syntactic sugar that allows you to guarantee that a resource is cleaned up without needing an explicit try-finally block. This means your code will be much cleaner, and you won't leak non-managed resources. Standard Dispose cleanup pattern, for objects that implement the IDisposable interf...
It is possible to use multiple nested using statements without added multiple levels of nested braces. For example: using (var input = File.OpenRead("input.txt")) { using (var output = File.OpenWrite("output.txt")) { input.CopyTo(output); } // output is ...
The following is a bad idea because it would dispose the db variable before returning it. public IDBContext GetDBContext() { using (var db = new DBContext()) { return db; } } This can also create more subtle mistakes: public IEnumerable<Person> GetPeople(int age)...
You don't have to check the IDisposable object for null. using will not throw an exception and Dispose() will not be called: DisposableObject TryOpenFile() { return null; } // disposable is null here, but this does not throw an exception using (var disposable = TryOpenFile()) { //...
Consider the following block of code. try { using (var disposable = new MyDisposable()) { throw new Exception("Couldn't perform operation."); } } catch (Exception ex) { Console.WriteLine(ex.Message); } class MyDisposable : IDisposable { public vo...
The using keyword ensures that the resource defined within the statement only exists within the scope of the statement itself. Any resources defined within the statement must implement the IDisposable interface. These are incredibly important when dealing with any connections that implement the IDi...
For some use cases, you can use the using syntax to help define a custom scope. For example, you can define the following class to execute code in a specific culture. public class CultureContext : IDisposable { private readonly CultureInfo originalCulture; public CultureContext(string ...
If you have code (a routine) you want to execute under a specific (constraint) context, you can use dependency injection. The following example shows the constraint of executing under an open SSL connection. This first part would be in your library or framework, which you won't expose to the client...

Page 1 of 1