Operators in Interfaces

An interface, as we all know, is a way of declaring members that a class must implement. This allows other classes that may only recognize the interface, to use a polymorphed version of the class and invoke the members that were defined in the interface.
One thing you can not declare inside an interface are operators. This makes perfect sense, because operators are declared as static and static members are defined per class (never you mind that apparently they can be inherited – a subject on which I posted before).
On the other hand, why can’t I do that? Take the following code for example:

public interface IIntegerHolder
{
    int Value { get; }
}

public class IntegerHolderImpl
{
    private int m_Value;

    public int Value { get { return m_Value; } };

    // More members...
}

public class Main
{
    static void Main(string[] args)
    {
        IntegerHolderImpl impl1 = new IntegerHolderImplementation(), impl1 = new IntegerHolderImpl();

        Console.WriteLine(Add(x, y));
    }

    static int Add(IIntegerHolder x, IIntegerHolder y)
    {
        return x.Value + y.Value;
    }
}

What happens if I want to implicitly convert an IIntegerHolder into an integer? Nope, you can’t do that, my compiler tells me.

Fine, I say, so I go and implement an implicit conversion on my implementing class:

public static implicit operator int(IIntegerHolder value)
{
    return value.Value;
}

After trying to build that, I get an error that the implicit conversion must convert to or from the enclosing type (IntegerHolderImpl).

So I change the code:

public static implicit operator int(IntegerHolderImpl value)
{
    return value.Value;
}

I also change the Add method so that it would look like this:

static int Add(IIntegerHolder x, IIntegerHolder y)
{
    return x + y;
}

And then I get an error that there is no implicit conversion from IIntegerHolder to int.

So our conclusion is that you can’t declare an operator per interface, no matter what. This pretty much sucks, because I would have expected one of these ways to work, even though they both have their flaws (the first defies the law that all operator must explicitly have a connection to the enclosing type; the second defies the laws of polymorphism).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s