Home > Software design >  C# create operator overload for concrete type of generic class or struct
C# create operator overload for concrete type of generic class or struct

Time:03-10

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?

CodePudding user response:

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);
    }
}

SharpLab.

  • Related