0

i have these two duplicated methods as extension methods , but i want to condense them into only one extension method ,

i have thought of using constraint : Where T : Struct ,

but then what about bool , other struct types , is there a way to limit only to int decimal float long etc.

   public static bool IsBetween(this double value, double lowerBound, double upperBound)
    {
        return value >= lowerBound && value <= upperBound;
    }


    public static bool IsBetween(this decimal value, decimal lowerBound, decimal upperBound)
    {
        return value >= lowerBound && value <= upperBound;
    }
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
Keshav Raghav
  • 347
  • 1
  • 12
  • 1
    There is currently no abstraction over different numeric types. The [shapes proposal](https://github.com/dotnet/csharplang/issues/164) might allow this in future. – canton7 Jan 08 '20 at 15:50
  • so is it that i have to duplicate for the types i want – Keshav Raghav Jan 08 '20 at 15:52
  • 1
    In general, yes. That is what the `Math` class currently does. In this specific case, you could write a generic method on types which are `IComparable` – canton7 Jan 08 '20 at 15:53
  • 2
    you don't *have* to - but it might be *simpler* to; you could also change `>=` and `<=` to checking `Comparer.Default.Compare(value, lowerBound)` etc, and test the reply -ve/0/+ve; this won't enforce things at compile-time, but it should *work* at least; it is probably *easier* just to write multiple methods, though – Marc Gravell Jan 08 '20 at 15:53
  • Given that this question is specifically about comparisons though, you could write `bool IsBetween(this T value, T lower, T upper) where T : IComparable` then use `value.CompareTo(lower)`, etc. Although the normal practice is to use `Comparer.Default`, restricting to `IComparable` would stop this extension method appearing for all types. I wish @CodeCaster hadn't closed it - I think there's a viable answer there. – canton7 Jan 08 '20 at 16:00
  • @CodeCaster I was failing to find a duplicate which had an answer which uses generics constrained to `IComparable`, but have since found one. I don't have the rights to add it as a dup, though: https://stackoverflow.com/questions/5023213/is-there-a-between-function-in-c/11252952 – canton7 Jan 08 '20 at 16:20
  • @canton are sure that's the one you mean? "Is there a “between” function in C#?" It _shows_ how to use that, but that's not really the question. – CodeCaster Jan 08 '20 at 16:24
  • 1
    @CodeCaster Yes. The OP's question is about an `IsBetween` method, and the 2nd answer in my proposed dup has the method I was suggesting. – canton7 Jan 08 '20 at 16:25

0 Answers0