Cyril Gandon
Cyril Gandon

Reputation: 17058

How to interface between implicit convertible type?

I have a class with a simple System.Drawing.Point (int, int).

public class Foo
{
    public Point Point;
}

I need that this class implement an interface with a PointF (float, float) :

public interface IPointable { PointF Point { get; } }

Of course, when I try Foo : IPointable, I have

Error   7   'Foo' does not implement interface member 'Pointable.Point'

So, I have change my Foo class with

public class Foo
{
    public Point IntPoint;
    public PointF Point { get { return IntPoint; } }
}

OUHAH, I compile. That's because Point have a implicit conversion to PointF :

public static implicit operator PointF(Point p);

But I feel dirty.

Foo have a Point with int coordinate, and this is important for a lot of my code. But sometimes, when Foo only need to be IPointable, his int-ness is not so much important.

Is there a way to not add a silly property to my class, and still Foo can be using the IPointable interface?

Upvotes: 0

Views: 771

Answers (2)

Rafal
Rafal

Reputation: 12619

You can implement interface explicitly:

internal interface IPointable
{
    PointF Point { get; }
}

internal class STH : IPointable
{
    public Point Point { get; set; }

    PointF IPointable.Point
    {
        get { return Point; }
    }
}

Now PointF property is only visible form variables that are typed IPointable.

Upvotes: 2

Adam Houldsworth
Adam Houldsworth

Reputation: 64487

No, you cannot optionally implement the interface members. The point of the interface is to define the public contract. By subscribing to the interface you are required to adhere to the contract.

If you want to leave the old Point property in place without changing it, implement the interface explicitly:

PointF IPointable.Point { get { return Point; } }

And use it by casting Foo to a reference of IPointable:

IPointable p = new Foo();

Upvotes: 2

Related Questions