Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the uses of "using" in C#?

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 using?

like image 970
ubermonkey Avatar asked Sep 16 '08 18:09

ubermonkey


People also ask

What is the use of using statement?

The using statement 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 can't be modified or reassigned. A variable declared with a using declaration is read-only.

Why do we use using in C#?

In C#, the using keyword has two purposes: The first is the using directive, which is used to import namespaces at the top of a code file. The second is the using statement. C# 8 using statements ensure that classes that implement the IDisposable interface call their dispose method.

What is using declaration in C#?

With the C# 8.0 update, Microsoft has introduced the using declaration feature. This feature allows us to declare a disposable object with the keyword using so the object will be disposed of when it goes out of the scope.

What is the use of in front of a variable in C#?

What is the @ symbol in front of variables in C#? From the C# documentation it states that the @ symbol is an Identifier. The prefix “@” enables the use of keywords as identifiers, which is useful when interfacing with other programming languages.


1 Answers

The reason for the using statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.

As in Understanding the 'using' statement in C# (codeproject) and Using objects that implement IDisposable (microsoft), the C# compiler converts

using (MyResource myRes = new MyResource()) {     myRes.DoSomething(); } 

to

{ // Limits scope of myRes     MyResource myRes= new MyResource();     try     {         myRes.DoSomething();     }     finally     {         // Check for a null resource.         if (myRes != null)             // Call the object's Dispose method.             ((IDisposable)myRes).Dispose();     } } 

C# 8 introduces a new syntax, named "using declarations":

A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.

So the equivalent code of above would be:

using var myRes = new MyResource(); myRes.DoSomething(); 

And when control leaves the containing scope (usually a method, but it can also be a code block), myRes will be disposed.

like image 169
paulwhit Avatar answered Oct 02 '22 15:10

paulwhit