Question: Can C# interfaces contain operators?
From searching, the answer I have found is no. For example, C# interface cannot contain operators
However, in Andrew Troelsen's book "Pro C# 5.0 and the .Net 4.5 framework" he makes the following statement
Alas, operator constraints are not supported under the current version of C#. However, it is possible (albeit it requires a bit more work) to achieve the desired effect by defining an interface that supports these operators (C# interfaces can define operators!) and then specifying an interface constraint of the generic class.
The sentence in bold is what puzzles me. Indeed, when I try the following
using System;
interface MathOps<T> where T : class
{
static T operator+(T a, T b);
}
class MyClass : MathOps<MyClass>
{
int x;
public MyClass(int n = 0)
{
x = n;
}
public static MyClass operator+(MyClass a, MyClass b)
{
return new MyClass(a.x + b.x);
}
}
class Program
{
static void Add<T>(ref T a, ref T b) where T : class, MathOps<T>
{
return a + b;
}
static void Main(string[] args)
{
}
}
The compiler throws the following back at me
error CS0567: Interfaces cannot contain operators
So the case kinda seems settled. But why does Mr Troelsen write the way he does? Am i missing/misinterpreting something?
Thanks.