Question

This

var h = new HashSet<int>();
var r = h.IsReadOnly;

does not compile. I have to do

var r = ((ICollection<int>)h).IsReadOnly;

why wasn't IsReadOnly implemented normally?

(I'm not asking how, but why)

Was it helpful?

Solution

I'm guessing its because, while HashSet implements ICollection, IsReadOnly has no meaning for HashSet. In fact, if you reflect it, the property always returns false. Implementing it explicitly hides this method from the public interface.

Another reason is because the ICollection interface may be implemented because of incidental reasons (e.g., to support xaml serialization) rather than because its necessary to the primary use of the class. So implementing it explicitly can keep the clutter out of the class' interface.

OTHER TIPS

There are basically two reasons why you would resort to an explicit interface implementation (source: MSDN):

  1. You implement multiple interfaces with members containing the same signatures, and you want these members to behave differently.
  2. An interface member is not of particular interest to the class, but is required in order to reference objects by the interface.

For HashSet<T>, the latter case applies, as a hash set is never read only and IsReadOnly will thus always return false.

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