Search code examples
c#templatesgenericsoperators

c++ 20 concepts alternative in c#


In c++ 20 we can use concepts which works like the where keyword in c# but I'm wondering how can i check T has some operator overloaded on it.

c++ Example:-

template <class T>
concept SupportPlusEqual = requires (T t) { t += t };

template <class T>
requires SupportPlusEqual <T>
void Add (T& lhs, T& rhs)
{
    lhs += rhs;
}

In this code T must have += operator defined.

Is there any way to do the same in c#?


Solution

  • I think the closest equivalent is if you use .NET 7, interfaces can now specify operators with the new static abstract and virtual members feature. For example:

    public interface IHasAdd<T> where T : IHasAdd<T>
    {
        static abstract T operator +(T a, T b);
    }
    

    To use it, make a type like this:

    public class Foo : IHasAdd<Foo>
    {
        public Foo(int someValue)
        {
            SomeValue = someValue;
        }
        
        public int SomeValue { get; init; }
        
        public static Foo operator +(Foo a, Foo b)
        {
            return new Foo(a.SomeValue + b.SomeValue);
        }
    }
    

    An example method that can use the interface:

    public T AddTogether<T>(T first, T second)
        where T : IHasAdd<T>
    {
        return first + second;
    }
    

    Which means you can now do this:

    var result = AddTogether(new Foo(1), new Foo(2));
    //result.SomeValue == 3