using System; namespace Core.Common.Utils.Extensions { /// /// Class defines extension methods for objects. /// public static class ComparableExtensions { /// /// Determines whether one object is greater than another. /// /// The first object. /// The second object. /// True if is considered greater then , /// false otherwise. /// null is considered smaller than any other not-null value. /// Object type of /// is not the same as that of . public static bool IsBigger(this IComparable object1, IComparable object2) { if (object1 == null) { return false; // Null not bigger then anything (or equal to null). } if (object2 == null) { return true; // Anything is greater then null. } return object1.CompareTo(object2) > 0; } /// /// Determines whether one object is smaller than another. /// /// The first object. /// The second object. /// True if is considered smaller then , /// false otherwise. /// null is considered smaller then any not-null value. /// Object type of /// is not the same as that of . public static bool IsSmaller(this IComparable object1, IComparable object2) { if (object1 == null) { return object2 != null; // smaller than anything but null } return object1.CompareTo(object2) < 0; } /// /// Determines where one object is within the inclusive bounds of some range. /// /// Value to be checked. /// First range value. /// Second range value. /// True if falls within the inclusive bounds, false otherwise. /// Object type of /// is not the same as that of or . public static bool IsInRange(this IComparable value, IComparable limit1, IComparable limit2) { IComparable min; IComparable max; if (limit1.IsSmaller(limit2)) { min = limit1; max = limit2; } else { min = limit2; max = limit1; } return (min.IsSmaller(value) && max.IsBigger(value)) || min.CompareTo(value) == 0 || max.CompareTo(value) == 0; } /// /// This method returns the clipped value of a value given an inclusive value range. /// /// A comparable object type. /// The value to be clipped. /// First range value. /// Second range value. /// The clipped value within the given validity range. /// Object type of /// is not the same as that of or . public static T ClipValue(this T value, T limit1, T limit2) where T : IComparable { T min; T max; if (limit1.IsSmaller(limit2)) { min = limit1; max = limit2; } else { min = limit2; max = limit1; } if (value.IsSmaller(min)) { return min; } if (value.IsBigger(max)) { return max; } return value; } } }