#region Copyright 2010-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0 /* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using System; using System.Collections.Generic; namespace CSharpTest.Net.Bases { /// Provides a base-class for non-reference equality objects [System.Diagnostics.DebuggerNonUserCode] public abstract class Equatable : IEquatable where T : Equatable { /// return a non-reference equality comparer for this class public static readonly EqualityComparer Comparer = new EqualityComparer(); /// Extracts the correct hash code protected abstract int HashCode { get; } /// Returns true if the other object is equal to this one public abstract bool Equals(T other); /// Returns true if the other object is equal to this one public sealed override bool Equals(object obj) { return Comparer.Equals(this as T, obj as T); } /// Extracts the correct hash code public sealed override int GetHashCode() { return Comparer.GetHashCode(this as T); } /// Compares the two objects for non-reference equality public static bool Equals(T x, T y) { return Comparer.Equals(x, y); } /// Compares the two objects for non-reference equality public static int GetHashCode(T obj) { return Comparer.GetHashCode(obj); } /// Compares the two objects for non-reference equality public static bool operator ==(Equatable x, Equatable y) { return Comparer.Equals(x as T, y as T); } /// Compares the two objects for non-reference equality public static bool operator !=(Equatable x, Equatable y) { return !Comparer.Equals(x as T, y as T); } /// Implements the equality comparer [System.Diagnostics.DebuggerNonUserCode] public sealed class EqualityComparer : EqualityComparer, IEqualityComparer { /// Compares the two objects for non-reference equality public override bool Equals(T x, T y) { if (((object)x) == null) return ((object)y) == null; if (((object)y) == null) return false; return x.Equals(y); } /// Extracts the correct hash code public override int GetHashCode(T obj) { return ((object)obj) == null ? 0 : obj.HashCode; } } } }