Back to: C#.NET Tutorials For Beginners and Professionals
Using Declarations in C# 8 with Examples
In this article, I am going to discuss Using Declarations in C# 8 with Examples. Please read our previous article where we discussed Pattern Matching Enhancements in C# with Examples. In order to understand the using declarations in C#, first, it is important to understand why they are needed.
Why do we need to use “Using Declarations” in C#?
In C#, as a programmer, we use the using statement for declaring disposable variables such as File I/O, databases, web services, etc. It ensures that classes that implement the IDisposable interface call their Dispose method. The only problem is that adding a using statement to our code introduces a new scope block. C# 8.0 using declarations eliminate this problem. It also guarantees that the Dispose method will be called, even if the code throws an exception.
By using the “using” keyword we can declare a variable that tells the compiler that the variable is declared should be disposed of at the end of the enclosing scope. If this is not clear at the moment then don’t worry, we will try to understand this concept with some examples.
What is IDisposable Interface in C#?
If you want to release the resources from an object, then you need to use the IDisposable interface in C#. So, what you need to do is, your class should inherit from the IDisposable interface and should implement the Dispose Function. This Dispose method provides a mechanism to release unmanaged resources. The following is the syntax for IDisposable.
Using Statement (Old Way) in C#
The using statement can be used to reference a variable or the result from a method, and at the end of the scope defined by the using statement, the Dispose method gets invoked. For a better understanding, please have a look at the below example. In the below example, first, the Resource will be created, then the resource will be used and when we go out of the using scope, the Dispose method will be automatically called and the resource will be disposed of.
using System; namespace Csharp8Features { public class UsingDeclarations { public static void Main() { using (var resource = new Resource()) { resource.ResourceUsing(); } // resource.Dispose is called here automatically Console.WriteLine("Doing Some Other Task..."); } } class Resource : IDisposable { public Resource() { Console.WriteLine("Resource Created..."); } public void ResourceUsing() { Console.WriteLine("Resource Using..."); } public void Dispose() { //Dispose resource Console.WriteLine("Resource Disposed..."); } } }
Output:
How is the Dispose Method automatically Called in C#?
When we use the using statement in C#, behind the scenes, the compiler will create a code block using try/finally to make sure Dispose method is also called even though an exception is thrown. This is because finally block gives you a guarantee to be executed irrespective of the exception thrown in the try block. So, for a better understanding, please have a look at the below image which shows our using statement code and the compiler-generated code.
Using Declarations (New Way) in C# 8
With the new C# 8 “using declarations”, the code with the using statement can be simplified. Now, the curly brackets are no longer required. At the end of the scope of the method (which is here the end of the main method), the Dispose method is also called automatically. Here also, the compiler creates a *try/finally block to make sure Dispose method is called. For a better understanding, please have a look at the below example.
using System; namespace Csharp8Features { public class UsingDeclarations { public static void Main() { using var resource = new Resource(); resource.ResourceUsing(); Console.WriteLine("Doing Some Other Task..."); } } class Resource : IDisposable { public Resource() { Console.WriteLine("Resource Created..."); } public void ResourceUsing() { Console.WriteLine("Resource Using..."); } public void Dispose() { //Dispose resource Console.WriteLine("Resource Disposed..."); } } }
Output:
Disposing Multiple Resources in C#:
When we use multiple resources, we are basically used to writing code that looks like the below with multiple nested using statements.
Example to understand Disposing Multiple Resources using Statement in C#:
using System; namespace Csharp8Features { public class UsingDeclarations { public static void Main() { using (var resource1 = new Resource()) { using (var resource2 = new Resource()) { resource1.ResourceUsing(); resource2.ResourceUsing(); } } Console.WriteLine("Main Method End..."); } } class Resource : IDisposable { public Resource() { Console.WriteLine("Resource Created..."); } public void ResourceUsing() { Console.WriteLine("Resource Using..."); } public void Dispose() { //Dispose resource Console.WriteLine("Resource Disposed..."); } } }
Output:
Now, let’s do the same with the new using declarations in C# 8. The following code is shorter compared to the previous one. no matter how many resources you need to dispose of.
Example to understand Disposing Multiple Resources using Declarations in C#:
using System; namespace Csharp8Features { public class UsingDeclarations { public static void Main() { using var resource1 = new Resource(); using var resource2 = new Resource(); resource1.ResourceUsing(); resource2.ResourceUsing(); Console.WriteLine("Main Method End..."); } } class Resource : IDisposable { public Resource() { Console.WriteLine("Resource Created..."); } public void ResourceUsing() { Console.WriteLine("Resource Using..."); } public void Dispose() { //Dispose resource Console.WriteLine("Resource Disposed..."); } } }
Output:
How to dispose of a resource before the method ends in C# using declarations?
In that case, we just need to add a separate scope using curly brackets. When the variable is out of scope, the resource is disposed of. For a better understanding, please have a look at the below example.
using System; namespace Csharp8Features { public class UsingDeclarations { public static void Main() { { using var resource1 = new Resource(); resource1.ResourceUsing(); }//resource1.Dispose() called here Console.WriteLine("Main Method End..."); } } class Resource : IDisposable { public Resource() { Console.WriteLine("Resource Created..."); } public void ResourceUsing() { Console.WriteLine("Resource Using..."); } public void Dispose() { //Dispose resource Console.WriteLine("Resource Disposed..."); } } }
Output:
Using Declarations vs. Using Statements in C#
In the case of using statements in C#, we need to write the try/finally block to ensure that an instance is disposed of in the finally block in case the try code block throws an exception. In the case of many IDisposable types, this would make the code very complex and crowded, as disposing of each instance requires blocks of try/finally code. On the other hand, using declarations in C# ensure that the object is disposed of when the code leaves the scope it is declared in. Hence, only the main method of a program changes by using declarations rather than using statements.
Realtime Example to Understand the using Declarations in C# 8:
Let’s consider the following example in which the file is disposed of when the method ends. Here, we are using the using declarations which was introduced as part of C# 8.
using System; using System.Collections.Generic; using System.IO; namespace Csharp8Features { public class UsingDeclarations { public static void Main() { WriteToFileUsingDeclaration(); Console.WriteLine("Main Method End..."); } public static void WriteToFileUsingDeclaration() { List<string> Statements = new List<string>() { "First Statement", "Second Statement", "Third Statement." }; using var file = new StreamWriter("MyTestFile.txt"); foreach (string Statement in Statements) { file.WriteLine(Statement); } }// file is disposed here } }
Note: If you go to the definition of StreamWriter class, then somewhere you will find that this class implements the Dispose method of the IDisposable interface. Further notice, this class implements the TextWriter abstract class and the TextWriter abstract class implements the IDisposable interface.
In the next article, I am going to discuss Static Local Functions in C# 8 with Examples. Here, in this article, I try to explain Using Declarations in C# with Examples. I hope you enjoy this Using Declarations in C# 8 with Examples article.