-3

I have been working with C# ASP.NET MVC5 for a while and I was wondering something. Why are we utilizing the using() to instantiate a class sometimes?

For an example:

using (CyrptoStream cs = new CryptoStream(PARAMETERS)
{
//SOMETHING
} 

or

using (Aes encryptor = Aes.Create()
{

}

How is that different to MyClass myClass = new MyClass()

Thank you.

Zagros
  • 142
  • 2
  • 10
  • 4
    Does this answer your question? [What are the uses of "using" in C#?](https://stackoverflow.com/questions/75401/what-are-the-uses-of-using-in-c) or [What is the C# Using block and why should I use it?](https://stackoverflow.com/questions/212198/what-is-the-c-sharp-using-block-and-why-should-i-use-it) – madreflection Feb 24 '20 at 21:01
  • This answered my question, thank you. – Zagros Feb 24 '20 at 21:34

1 Answers1

1

using cleans up after itself when control leaves the scope block. Use it to ensure Dispose is called on the object that was created in the top line (next to using)

Multiple using blocks can be nested, though the neater form is to see them stacked in a line with only the bottom one having curly brackets

using(X x = new X())
using(Y y = new Y())
using(Z z = new Z())
{
  //code here
}

However it comes to be that control leaves the //code here part (return, reaching the end, throwing exception etcp) we can guarantee that x.Dispose(), y.Dispose() and z.Dispose() will be called. Not everything has to be disposed, which is why we don't see using all over the place, but for some things ensuring Dispose is called is highly advisable in order to free up resources. The documentation for whatever library you're using will advise on whether disposing is recommended. Some prime examples in everyday c# use where disposal is recommended are database connections, graphics/gdi drawing, stream writing.. if you're unsure whether to dispose something or not, take a look at it in the object browser and see if it implements IDisposable; if it does then err on the side of caution and dispose it when you're done with it, but don't dispose of anything you didn't create (it's not your job to do so)

Caius Jard
  • 72,509
  • 5
  • 49
  • 80