Alex Rivera | Logout

Why is HashSet<T>.IsReadOnly explicit?

Asked 2009-04-13T09:59:31.117
12

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)

Edit
Report

1 Answer

17

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.

answered 2009-04-13T10:17:53.337

Your Answer