Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does adding IDisposable change the semantics of a class?

The MSDN documentation for IDisposable states that:

It is a version-breaking change to add the IDisposable interface to an existing class, because it changes the semantics of the class.

What exactly does this mean?

I can see how removing IDisposable would be a big deal. Instantiating a class inside of a using statement would no longer be possible, for example. But what else makes IDisposable special, especially in the context of adding the interface?

like image 965
Jonathon Reinhart Avatar asked Jan 12 '23 16:01

Jonathon Reinhart


2 Answers

When you implement IDisposable, you're basically adding semantics of "you should dispose this when you're done with it". That means that existing code which doesn't dispose of it is violating that implicit contract... so there's no way of going from "not implementing IDisposable" to "implementing IDisposable" while keeping clients using your type correctly, unless you also have access to all that client code.

To give another example - suppose the documentation for GetHashCode was updated to say "This should always return an even number" - that would be a breaking change because existing code could easily return an odd number. Again, it wouldn't break in source code - everything would still build - but you'd be changing the contract to make it more restrictive.

If you view the implementation of IDisposable as a contract on the client code, hopefully it's clearer why it's a breaking change.

like image 162
Jon Skeet Avatar answered Jan 31 '23 00:01

Jon Skeet


Implementing IDisposable tells clients that they always need to dispose the class.

That is a breaking change.

like image 27
SLaks Avatar answered Jan 30 '23 23:01

SLaks