I have a C# extension method as follows:
public static double RoundOff(this double rawNumber, double roundToNearest)
{
double rawMultiples = rawNumber / roundToNearest;
double roundedMultiples = Math.Round(rawMultiples);
double roundedNumber = roundedMultiples * roundToNearest;
return roundedNumber;
}
I don't want to write it multiple times for all the different numeric types (int, decimal, etc.)
Is there a way to do it generically, like this?
public static double RoundOff<T>(this T rawNumber, T roundToNearest)
where T : [SOME CONSTRAINT]
{
T rawMultiples = rawNumber / roundToNearest;
T roundedMultiples = Math.Round(rawMultiples);
T roundedNumber = roundedMultiples * roundToNearest;
return roundedNumber;
}
It would be so so useful to be able to do this more generally. Less code to maintain - and more power from just one extension method!
If it can't be done, is it because C# can't be extended to work in this way? Or might it one day be extended to allow an "all numeric types" generic constraint?
Any ideas welcomed.
UPDATE In response to a challenge about similarity to another question. Yes, it is similar in terms of the subject matter but is different because I am after a specific solution to a specific problem. I have added my own attempted answer below to clarify. Challenges welcome if anyone still thinks I have missed the point.