Introduction
In C# 8, the using declaration syntax was introduced. This gives our code the benefits of IDisposable, without the extra noise that using statements can introduce.
IDisposable
If our class has some expensive resource allocation, we might want to deterministically free that resource as soon as we're done using it. We achieve this in C# by implementing the IDisposable interface. You must define a Dispose() method, and within that method you can free any resources explicitly.
- class Resource : IDisposable
- {
- public Resource()
- {
- Console.WriteLine("Resource created...");
- }
- public void Dispose()
- {
- Console.WriteLine("Resource disposed..");
- }
- }
The Old Way
Since we're following the IDisposable convention, we can use the using statement syntax which will automatically call Dispose() when the scope ends.
- using (var resource = new Resource())
- {
- Console.WriteLine("Using resource...");
- }
Output
- Resource Created...
- Using resource...
- Resource Disposed...
The New Way, C# 8 Using Declarations
- using var resource = new Resource();
- Console.WriteLine("Using resource...");
Output
- Resource Created...
- Using resource...
- Resource Disposed...
Example - File I/O
- try
- {
- using var sr = new StreamReader("test.txt");
- Console.WriteLine(sr.ReadToEnd());
- }
- catch (IOException e)
- {
- Console.WriteLine("Error while loading the file.");
- }
Conclusion
This syntax feature is so simple, and can not only reduce extra indentations in your code, I think it also reduces cognitive burden when reading the code.
As always I hope you find this article helpful. Please share any feedback or article suggestions. Thanks for reading!