Question

In overall cases, the Close method semantically just change the state of a object that can be changed again with the Open method, indefinitely.

In other hand the semantics of IDisposable.Dispose() method put the object in a state that cannot be undone.

So, why several answers about "close x dispose" and even MSDN pattern shows Close method calling Dispose ?

Was it helpful?

Solution

There is plenty of friction about this is the .NET framework itself. The implementation is however consistently without surprise, a class' Close() method always calls its Dispose() method.

Logically it always means the exact same thing. You explicitly say "I don't use this object anymore" in your code. So of course Close() just means the exact same thing as Dispose(). They both mean the exact same thing, "I'm done using it". So of course the implementation of these methods do the exact same thing.

Semantically it however does not mean the same thing. The big dog is the using statement.

You, preferably, never call Dispose() explicitly. The only place is should ever appear in your code is in your own IDisposable implementation. Which you need to implement when your class has members that implement IDisposable themselves. Which obliges you to implement IDisposable yourself, you simply implement it by calling the members' Dispose method.

Which is the only place you ever use it. In any other usage, you leave it up to the using statement inside of a method to automatically call Dispose() for you. With the corner-case that you don't want to dispose right away, you may need to keep the object around beyond the method call. That's when you use the Close() method.

OTHER TIPS

Your initial statement:

In overall cases, the Close method semantically just change the state of a object that can be changed again with the Open method, indefinitely.

Is false. At least, it's false in terms of major .NET Framework classes.

In my experience, it's not often safe to write obj.Close(); followed by obj.Open();. Some classes support such behavior, but it's certainly not a hard and fast rule. I wouldn't bet that it's true in 50% of cases.

StreamReader.Close, calls Dispose. Stream.Close calls Dispose. SqlConnection.Close calls Dispose. From the SqlConnection remarks:

Close and Dispose are functionally equivalent.

I'm sure that there are cases in which Close does not call Dispose, but I would not suggest betting on the idea that Close can be followed by Open.

It's the other way around. Usually the Dispose method calls Close.

If the Close method of a class is implemented to call Dispose, then it's because closing and disposing are the same. Once you have closed it, you can't reopen it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top