What is the purpose of the Using
block in C#? How is it different from a local variable?
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.
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.
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.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With