Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#

What is using declarations in C#?

Samia Ishaque

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

To understand the using declarations in C#, it is important to understand why they are needed. The using declarations were preceded by using statements, which introduced a lot of noise and extra code blocks in the program. Using declarations is a much simpler way of benefitting from iDisposable.

What is iDisposable?

If you need to free up resources from an object, you use the iDisposable interface. You define a function dispose for this purpose. The general syntax for iDisposable is as shown below:

class Resource : IDisposable  
{  
    public Resource()  
    {  
       #do something
    }  
    public void Dispose()  
    {  
       #dispose resource
    }  
} 

Using declarations vs. using statements

In the case of using statements, you have to use the try/finally method to ensure that an instance is disposed of in the finally code 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 codes.

On the other hand, using declarations 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 with using declarations rather than using statements.

Example

The following code highlights the aforementioned differences between using declarations and using statements.

As shown below, using statements call the Dispose function, whereas using declarations dispose of the instance test when the scope of its declaration ends.

//using statements
private static void Main(string[] args)
{
Test test = new Test();
try
{
test.function();
}
finally
{
if (test != null)
{
test.Dispose();
}
}
}
//using declarations
static void Main(string[] args)
{
using var test = new Test();
test.function();
}

RELATED TAGS

c#

CONTRIBUTOR

Samia Ishaque
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring