1

I'm currently trying to write an extension method to work out the allowed variance for a decimal. While I was writing it I thought I'd extend it to a generic extension, with restrictions to decimal, float, double.

Currently I'm not aware of how (or if it's possible) to restrict a generic to value types.

public static bool WithinVariance(this decimal source, decimal allowedVariance, decimal comparisonValue)
        => WithinVariance<decimal>(source, allowedVariance, comparisonValue);

public static bool WithinVariance<T>(T source, T allowedVariance, T comparisonValue)
    // where T : decimal
    // where T : double
    // where T : float 
{
    var allowedDifference = (source / 100) * allowedVariance;
    var difference = source - comparisonValue;
    return Math.Abs(difference) <= allowedDifference;
}

The above code doesn't work, it's there purely to show the approach I'm taking. Originally I was just going to a single method, but I changed to the above to try to hack it into working. Also an attempt at restricting the extension methods without using a where t filter (see commented out lines)

Does anyone know if it's possible and if so how to do this?

Monofuse
  • 735
  • 6
  • 14
  • 2
    Restricting it to "just value types" wouldn't help much, because it doesn't make sense for (say) Guid. You could restrict it to types implementing `IComparable`, and specify min and max values. But *at the moment* there's no easy way of implementing that specific signature. (That may change in C# 8 or 9.) – Jon Skeet Mar 29 '19 at 11:26
  • 1
    Although the above question talks about `int`s I think it's applicable to this one – Magnetron Mar 29 '19 at 11:32
  • I didn't come across that question during my search for similar posts. You are right it is a duplicate and after looking at it, the "answer" was recently updated even though the post is 10 years old. – Monofuse Mar 29 '19 at 11:33
  • Look at [`Enumerable.Max`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.max?view=netframework-4.7.2) – Damien_The_Unbeliever Mar 29 '19 at 11:33
  • 1
    It seems they (Microsoft) was thinking about a common interface for numerics (IArithmetic), https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/int32.cs – Magnus Mar 29 '19 at 12:09

0 Answers0