5

Suppose I have a class that is a readonly collection or immutable objects, e.g.

public class ReadOnlyInts : IReadOnlyCollection<int>
{
    private readonly IReadOnlyCollection<int> intCollection;
    public ReadOnlyInts(IEnumerable<int> ints)
    {
        intCollection = ints.ToList().AsReadOnly();
    }

    #region IReadOnlyCollection<int> Methods
    // ...
    #endregion
}

Now, without some trickery on the part of the consumer neither the intCollection nor its members can change so the type is immutable. Going by the MSDN guidelines, the type should overload ==. However, it is not clear to me that these guidelines are intended to apply to collections as the .Net built in collections do not override even .Equals. I am worried then that overloading == as roughly .SequenceEquals will be unexepected behavior to other consumers.

Is it a good idea for deeply immutable collections to overload ==?

1

If you construct two different ReadOnlyInts, but they have the same content (perhaps created from the same IEnumerable<int> object) do you want them to be equal? If so then you should overload == and check the contents for equality. Otherwise it's just a reference comparison which will fail with two different but identical objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.