I have an object that needs to be serialized and de-serialized due to it being persistently stored as part of Service Fabric reliable collections.

The object StreamResourceUsage has two members:

        /// <summary>
        /// Gets or sets the account name for this detailed data
        /// </summary>
        [DataMember]
        public string AccountName { get; set; }

        /// <summary>
        /// Gets or sets the stream information for that account.
        /// </summary>
        [DataMember]
        public List<StreamInfo> StreamInformation { get; set; }

Since I want the class StreamResourceUsage to implement both

IEquatable<StreamResourceUsage>
IComparable<StreamResourceUsage>

I want comparing two StreamResourceUsage to be equal if and only if the elements in the list are all equal.

Before comparing two objects as part of the CompareTo method: public int CompareTo(StreamResourceUsage other)

I sorted the two lists (this and other)

However, the CompareTo method should not be modifying the lists, since that might cause problems in multi-threaded environment for example.

I know I can sort the list in the constructor after it's deeply copied and passed in. However, since it is a data member and public, I cannot control bad outside behavior or re-arranding list elements.

What would be the best approach here?

  1. In the CompareTo method, instead of sorting, just compare the elements by keeping a temp hashSet or dictionary to compare corresponding elements effectively. This does not solve the problem that the list can be modified from the outside. But the latter can be solved by using an ImmutableList for e.g
  2. Make the list private (and not a DataMember) while exposing another list as data member which is a deep copy of the internal list. Even if it is modified, it will not modify internal structure. If the list is private, it can be sorted in the CompareTo method just fine without causing problems since it is not exposed.
0

There are 0 best solutions below