views:

423

answers:

2

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)

+9  A: 

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.

Will
+1 That sounds reasonable.
Andrew Hare
Ah, yes, that does make sense. HashSet also hides IsReadOnly for the same reason I guess, hence the compile error if you try to use it.
Steve Haigh
BTW, you don't need to implement ICollection for xaml serialization; collections must implement IDictionary or IList. It was just an example of occasions when you might need to implment an interface for incidental reasons.
Will
+4  A: 

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.

Tormod Fjeldskår