-1

Everybody knows that using keyword is used when we want to clean up the unmanaged resources.

If the class implements IDisposable then we can use using keyword with the object of that class. But if I want to use using keyword with the object of my own class then how can I use it.

If I had to implement IDisposable in my own class then I have to also write the code for its Dispose() method in my class. Then there is no point of using the using keyword here when I am writing my own code in Dispose() method. Then how can I use using in a user defined type (like classes & structs).

Please explain with some example.

Tim B James
  • 20,084
  • 4
  • 73
  • 103
Puneet Pant
  • 918
  • 12
  • 37
  • Less of the down votes folk. This is just a learning curve for some people! – Tim B James Feb 02 '13 at 09:59
  • 2
    so much for helping each other. I wonder of 6 downvotes add a lot... – bas Feb 02 '13 at 10:01
  • 2
    Nothing's wrong with the question. I don't understand the down-votes. – Sina Iravanian Feb 02 '13 at 10:05
  • I am not going to write an example down, as you would be better just reading this article. [Implementing IDisposable and the Dispose Pattern Properly](http://www.codeproject.com/Articles/15360/Implementing-IDisposable-and-the-Dispose-Pattern-P) - on the Code Project website. – Tim B James Feb 02 '13 at 10:18

3 Answers3

5

The point of the using keyword is that it calls Dispose() on the instance of your class for you, so you don't have to write myDisposableObject.Dispose() yourself when you're done using it. It doesn't help you write that method — you still have to write it yourself to tell the framework how exactly you want your unmanaged resources to be disposed.

I'm not sure what kind of example you're looking for, since you clearly know how to implement the IDisposable interface and its Dispose() method. All I can say here is if you don't have any unmanaged resources to dispose (or members that are themselves IDisposable), then don't implement IDisposable, and don't use using. That keyword is reserved only for conveniently using things that do have unmanaged resources that would otherwise need manual cleanup.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
2

The point of using is not to relieve you from implementing IDisposable.

The point of using is to allow you to ensure that the object will be properly disposed when the flow exits the block either normally or due to an exception.

Theodoros Chatzigiannakis
  • 28,773
  • 8
  • 68
  • 104
0

The using statement calls the Dispose method of the the used object upon termination of the block. See this to see how a using block is compiled.

However, it is your responsibility to implement the Dipose method, in which you have to free the resources occupied by the object.

Community
  • 1
  • 1
Sina Iravanian
  • 16,011
  • 4
  • 34
  • 45