2

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.

Community
  • 1
  • 1
jensa
  • 2,792
  • 2
  • 21
  • 36
  • 3
    Interfaces cannot contain static methods. Not that removing the *static* keyword gets you anywhere. Beware that books like that tend to suffer from poor editing, it *might* have been possible in .NET 1.x. The CLR doesn't care that an interface has an operator, it is just a method with a funny name. A minor hint that might have been the case is that the offline copy of MSDN I use does not have CS0567 in the index. You are wasting your time on this. – Hans Passant Nov 26 '15 at 20:30
  • @HansPassant Thanks, yeah I agree with you that it looks like the book needs some more editing. I won't put more effort into this, interfaces can't contain operators, period. – jensa Nov 26 '15 at 20:41

1 Answers1

0

One key to remember is that, as far as I know, it's not so much that an interface cannot define operators (though that is true) but that interfaces cannot define statics, which is frustrating but also logical.

Brian McBrayer
  • 163
  • 2
  • 8
  • I'm curious why the downvote? I'm not arguing against, but a downvote without a comment doesn't help me to learn anything. :) And also, I *think* that what I said is true. – Brian McBrayer Nov 30 '15 at 05:19
  • This has obviously changed with C# 8. Interfaces can now define static methods, but still cannot define [operators](https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs0567) – Durdsoft Mar 04 '20 at 15:40