Search code examples
c#wcfequality

Use Non-Readonly property in GetHashCode with DataMember attribute


I use a DataContract to handle a class in a WCF-Service. Therefore I need the property ApiCallStatus (type: ApiCallStatus as Enum) to have a both auto-getter and -setter. But for the override of GetHashCode I need a "readonly" property to implement it correctly. Is there a way to implement this in a way that both requirements work correctly and are implemented in a clean way?

[DataContract]
public class ApiCallStatusInformation {
    [DataMember]
    public ApiCallStatus ApiCallStatus { get; set; }

    public bool Equals(ApiCallStatusInformation other) {
        if (ReferenceEquals(null, other))
            return false;
        if (ReferenceEquals(this, other))
            return true;

        return this.ApiCallStatus == other.ApiCallStatus;
    }

    public override bool Equals(object obj) {
        if (ReferenceEquals(null, obj))
            return false;
        if (ReferenceEquals(this, obj))
            return true;
        return obj.GetType() == this.GetType() && this.Equals((ApiCallStatusInformation) obj);
    }

    public override int GetHashCode() {
        return (int) this.ApiCallStatus;
    }
}

Solution

  • A [DataMember] may be private readonly, which avoids this issue.

    The reason it can be private readonly is that the [DataContract] implementation uses reflection to set the [DataMember] fields, which means that the private and readonly aspects are ignored.