| | | 1 | | namespace ArturRios.Extensions; |
| | | 2 | | |
| | | 3 | | /// <summary> |
| | | 4 | | /// Provides comparison helpers and syntactic sugar for checking membership (In/NotIn). |
| | | 5 | | /// </summary> |
| | | 6 | | public static class ComparisonExtensions |
| | | 7 | | { |
| | | 8 | | /// <summary> |
| | | 9 | | /// Returns true if the value is equal to any element in the provided range. |
| | | 10 | | /// </summary> |
| | | 11 | | /// <typeparam name="T">Type of the value and of the range elements.</typeparam> |
| | | 12 | | /// <param name="self">The value to look for.</param> |
| | | 13 | | /// <param name="range">Values to compare against. An empty range never matches.</param> |
| | | 14 | | /// <returns>True if a match is found; otherwise false.</returns> |
| | | 15 | | /// <exception cref="ArgumentNullException"><paramref name="range"/> is <c>null</c>.</exception> |
| | | 16 | | /// <remarks> |
| | | 17 | | /// <para> |
| | | 18 | | /// Equality is decided by <see cref="EqualityComparer{T}.Default"/>, so a type that overrides |
| | | 19 | | /// <see cref="object.Equals(object)"/> or implements <see cref="IEquatable{T}"/> is honoured, and two |
| | | 20 | | /// nulls compare equal without either side having to be dereferenced. |
| | | 21 | | /// </para> |
| | | 22 | | /// <para> |
| | | 23 | | /// Declared as a classic extension method rather than in an <c>extension</c> block: the compiler |
| | | 24 | | /// reports a spurious nullability warning (CS8620) for every argument of an expanded <c>params</c> |
| | | 25 | | /// call to an extension-block member, so <c>2.In(1, 2, 3)</c> produced three warnings in every |
| | | 26 | | /// consumer with nullable reference types enabled. |
| | | 27 | | /// </para> |
| | | 28 | | /// </remarks> |
| | | 29 | | public static bool In<T>(this T self, params T[] range) |
| | | 30 | | { |
| | 32 | 31 | | ArgumentNullException.ThrowIfNull(range); |
| | | 32 | | |
| | 94 | 33 | | return Array.Exists(range, other => EqualityComparer<T>.Default.Equals(self, other)); |
| | | 34 | | } |
| | | 35 | | |
| | | 36 | | /// <summary> |
| | | 37 | | /// Returns true if the value is not equal to any element in the provided range. |
| | | 38 | | /// </summary> |
| | | 39 | | /// <typeparam name="T">Type of the value and of the range elements.</typeparam> |
| | | 40 | | /// <param name="self">The value to look for.</param> |
| | | 41 | | /// <param name="range">Values to compare against. An empty range never matches, so the result is true.</param> |
| | | 42 | | /// <returns>True if no match is found; otherwise false.</returns> |
| | | 43 | | /// <exception cref="ArgumentNullException"><paramref name="range"/> is <c>null</c>.</exception> |
| | 10 | 44 | | public static bool NotIn<T>(this T self, params T[] range) => !self.In(range); |
| | | 45 | | } |