Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading