views:

192

answers:

3

I'm using interface for most of my stuff. I can't find a way to create an overload operator + that would allow me to perform an addition on any objects implementing the IPoint interface

Code


interface IPoint
{
    double X { get; set; }
    double Y { get; set; }
}


class Point : IPoint
{
   double X { get; set; }
   double Y { get; set; }

   //How and where do I create this operator/extension  ???
   public static IPoint operator + (IPoint a,IPoint b)
   {
     return Add(a,b);
   }

   public static IPoint Add(IPoint a,IPoint b)
   {
      return new Point { X = a.X + b.X, Y = a.Y + b.Y };
   } 
}

   //Dumb use case :
public class Test
{
   IPoint _currentLocation;

   public Test(IPoint initialLocation)
   {
     _currentLocation = intialLocation
   }
   public MoveOf(IPoint movement)
   {

      _currentLocation = _currentLocation + intialLocation;
     //Much cleaner/user-friendly than _currentLocation = Point.Add(_currentLocation,intialLocation); 
   }
}

+3  A: 

You don't. Imagine if you have two IPoint instances, a and b, both of different classes (which implement IPoint). Now call "a + b". Which operator+ gets called? Which concrete type is returned?

Edit: Sorry, to clarify to your comment, "Not in C# as it stands". I have some philipsophical debate as to whether you should even be able to do this, as I suspect you can create some significant confusion.

Adam Wright
That is the point of the question : Is there a way to write an overload (like in C++) that is NOT attached to a specific class. In my case, I want the operator I'm defining to be called when 2 instance of IPoint are called.
+1  A: 

As Eric Lippert put it, can't be done right now :(

Thanks

A: 

I don't think you can do what you're asking, I've looked in the past and come up empty. The problem is, even in your example of using .Add is that you still need to cast the movement parameter to a Point Type to have access to that method. This, I believe is a limitation of C#, if I'm wrong I'd be very happy to know about it.

What I would suggest is that if you know you are always going to get a Point Type in MoveOf then it would be safe to always cast it to Point inside the method, however if this is the case then you should be accepting Point as the parameter.

The only other thing I can say is that if you are creating a Point Type initially and passing that to MoveOf, you could check the type of movement inside MoveOf before casting it. The problem here of course is that you would eventually have to do this for all types that inherit from IPoint and use the MoveOf method.

Alexander Kahoun