2010-04-06

Sharp Corners: IList<T>.IsReadOnly != IList.IsReadOnly

Here's a "sharp corner" of sorts, though it's with the BCL rather than the C# language. It turns out that the property IsReadOnly changed meanings from IList to IList<T>. As of this writing, it's unclear whether this change in meaning was intentional; the MSDN documentation for both properties is identical (and ambiguous).

[TestMethod]
public void IListOfT_IsReadOnly_IsDifferentThan_IList_IsReadOnly()
{
    int[] array = new[] { 13 };
    IList<int> generic = array;
    System.Collections.IList nongeneric = array;

    Assert.AreNotEqual(generic.IsReadOnly, nongeneric.IsReadOnly);
}

3 comments:

  1. I believe this behavior is intentional, but I have no way of knowing if I am right or not. :)

    In the non-generic IList, you used to have two properties for read-onlyness - IsReadOnly and IsFixedSize.

    IList.IsFixedSize returns true if
    * number of elements could not be changed

    IList.IsReadOnly returns true if
    * number of elements could not be changed
    AND
    * individual elements could not be changed

    With the generic collections, IsFixedSize was removed, and IsReadOnly was moved to ICollection<T>.

    The new IsReadOnly seems to have the following semantics:

    ICollection<T>.IsReadOnly returns true if
    * number of elements could not be changed
    OR
    * individual elements could not be changed

    This is my best understanding, but I reserve the right to be wrong... :)

    ReplyDelete
  2. I agree with your interpretation; I did cover this in more detail here:
    http://nitoprograms.blogspot.com/2009/11/icollection-isreadonly-and-arrays.html
    which I meant to link to in this blog post (and forgot)...

    ReplyDelete
  3. Ah, d'oh... I missed that post!

    ReplyDelete