I am implementing a custom collection implementation that can either be readonly or non-readonly; that is, all the methods that change the collection call a function that is the moral equivalent of:
private void ThrowIfReadOnly() {
if (this.isReadOnly)
throw new SomeException("Cannot modify a readonly collection.");
}
I am not sure which of NotSupportedException or InvalidOperationException I should use in that case.
The MSDN only has one bit of guidance on this precise topic, on
NotSupportedException:What follows is purely my own interpretation of the rule:
InvalidOperationExceptionshould be used.NotSupportedExceptionshould be used.Dispose()call that often makes most other instance methods unusable;ObjectDisposedExceptiontype should be used. (That is still a subtype ofInvalidOperationException).The practical application of these rules in that case would be as follows:
isReadOnlycan only be set at the time when the object is created (e.g. a constructor argument), and never at any other time, thenNotSupportedExceptionshould be used.isReadOnlycan change during the lifetime of the object, thenInvalidOperationExceptionshould be used.InvalidOperationExceptionvsNotSupportedExceptionis actually moot in the case of implementing a collection – given the description ofIsReadOnlyon MSDN, the only permitted behavior forIsReadOnlyis that its value never changes after the collection is initialized. Meaning that a collection instance can either be modifiable or read-only – but it should choose one at initialization and stick with it for the rest of its lifetime.