'C# create operator overload for concrete type of generic class or struct
My type CRange<T> is defined as
public readonly struct CRange<T>
where T : struct, IComparable
{
...
public T LowerValue { get; }
public T UpperValue { get; }
}
Unfortunately, there is no where T: Number.
I mainly use CRange<int> and CRange<double>, and there are a couple of situations where I want to multiply a CRange<> with a factor (= double).
I tried
public static CRange<double> operator * (CRange<double> i_range, double i_factor)
but this is not allowed, because each operator must contain at least one operand of the type.
Is there any other way to create such an operator?
Solution 1:[1]
You can write an extension method -- this is what the runtime does for e.g. Vector128<T>. This does mean you need a method rather than an operator however.
public static class CRangeExtensions
{
public static CRange<double> Multiply(this CRange<double> range, double factor)
{
return new CRange(range.LowerBound * factor, range.UpperBound * factor);
}
// Same for int...
}
If you're OK using preview features, you can make use of Generic math which defines the INumber<T> interface:
public readonly struct CRange<T> where T : INumber<T>
{
public T LowerValue { get; }
public T UpperValue { get; }
public CRange(T lower, T upper) => (LowerValue, UpperValue) = (lower, upper);
public static CRange<T> operator * (CRange<T> range, T factor)
{
return new CRange<T>(range.LowerValue * factor, range.UpperValue * factor);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | canton7 |
