Search code examples
c#variablesusing

Declaring and initialising a variable in a using block


After a bit of advice here, regarding best practice coding - I am still a beginner with regards to C#. I have been reading on how using blocks are essential for disposing objects and attempting to implement these.

My question however, is if you are declaring and initialising a variable, should this be in a using block also?

I have tested and it seems to compile fine. But would appreciate peoples thoughts on this.

Thanks,


Solution

  • Using blocks are only helpful with objects that implement the IDisposable interface. It roughly translates to having a try...finally block that disposes the object in the finally. You can see more detail here.