Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the C# Using block and why should I use it? [duplicate]

What is the purpose of the Using block in C#? How is it different from a local variable?

like image 308
Ryan Michela Avatar asked Oct 17 '08 13:10

Ryan Michela


People also ask

What is C -- used for?

C-- is a "portable assembly language", designed to ease the implementation of compilers that produce high-quality machine code. This is done by delegating low-level code-generation and program optimization to a C-- compiler.

What is C language in simple words?

C is a structured, procedural programming language that has been widely used both for operating systems and applications and that has had a wide following in the academic community. Many versions of UNIX-based operating systems are written in C.

What is history of C language?

C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T (American Telephone & Telegraph), located in the U.S.A. Dennis Ritchie is known as the founder of the c language. It was developed to overcome the problems of previous languages such as B, BCPL, etc.


2 Answers

If the type implements IDisposable, it automatically disposes that type.

Given:

public class SomeDisposableType : IDisposable {    ...implmentation details... } 

These are equivalent:

SomeDisposableType t = new SomeDisposableType(); try {     OperateOnType(t); } finally {     if (t != null) {         ((IDisposable)t).Dispose();     } } 
using (SomeDisposableType u = new SomeDisposableType()) {     OperateOnType(u); } 

The second is easier to read and maintain.


Since C# 8 there is a new syntax for using that may make for more readable code:

using var x = new SomeDisposableType(); 

It doesn't have a { } block of its own and the scope of the using is from the point of declaration to the end of the block it is declared in. It means you can avoid stuff like:

string x = null; using(var someReader = ...) {   x = someReader.Read(); } 

And have this:

using var someReader = ...; string x = someReader.Read(); 
like image 184
plinth Avatar answered Oct 12 '22 13:10

plinth


Using calls Dispose() after the using-block is left, even if the code throws an exception.

So you usually use using for classes that require cleaning up after them, like IO.

So, this using block:

using (MyClass mine = new MyClass()) {   mine.Action(); } 

would do the same as:

MyClass mine = new MyClass(); try {   mine.Action(); } finally {   if (mine != null)     mine.Dispose(); } 

Using using is way shorter and easier to read.

like image 41
Sam Avatar answered Oct 12 '22 13:10

Sam