-1

I'm sure this is an easy question, but what am I supposed to do when handling an IDisposable object without the using statement?

Phate01
  • 2,499
  • 2
  • 30
  • 55
  • 4
    yourObject.Dispose(); <-- Just add that before leaving the method you're working in. – Falgantil Feb 23 '15 at 13:23
  • 2
    Probably because it's a question that is answered by reading the first result when Googling 'c# using' – Falgantil Feb 23 '15 at 13:25
  • _what am I supposed to do when ..._ - add a `using(){}` statement? The question isn't very clear or complete. Please elaborate on the what and why. – H H Feb 23 '15 at 13:26
  • Welcome recent user to SO. What research have you done? What have you tried? –  Feb 23 '15 at 13:27
  • Searched both google and stackoverflow about this _specific_ question, I decided to ask question here to have a little bit more support, having found anything. Clearly I haven't got how to ask questions here – Phate01 Feb 23 '15 at 13:35

1 Answers1

5

All the using construct does is call on Dispose() which IDisposable mandates you implement.

So you can just call it yourself, instead of:

using (IDisposable something = new SomeDisposableClass()) {
    ...
}

Do:

IDisposable something = new SomeDisposableClass();

try {
   ...
} finally {    
   something?.Dispose();
}

Notice the use of the try..finally which will ensure Dispose() is called even if there is an exception.

Lloyd
  • 29,197
  • 4
  • 84
  • 98