tags:

views:

161

answers:

3

Was a bit shocked to discover that System.Drawing.PointF appears to have operators for subtracting sizes but not other PointFs. So I'm trying to write my own PointF class, but it needs to be able to have System.Drawing.Points automatically converted to it, or it really doesn't add any convenience. So I wrote these constructors:

    public PointF(float x = 0, float y = 0)
    {
        this.x = x;
        this.y = y;
    }

    public PointF(System.Drawing.PointF p) : this(p.X, p.Y) { }
    public PointF(System.Drawing.Point p) : this(p.X, p.Y) { }

But I'm still getting this error:

cannot convert from 'System.Drawing.Point' to 'my_namespace.PointF'

(I have a function that accepts a my_namespace.PointF but I'm passing in a System.Drawing.Point).

Shouldn't the 3rd constructor kick in and auto-convert it?

+3  A: 

Do you have an implicit conversion defined in your my_namespace.PointF class? It won't automatically convert otherwise.

public PointF(float x = 0, float y = 0)
{
    this.x = x;
    this.y = y;
}

public PointF(System.Drawing.PointF p) : this(p.X, p.Y) { }
public PointF(System.Drawing.Point p) : this(p.X, p.Y) { }

//add this:
public static implicit operator PointF(System.Drawing.Point pt) 
{ return new PointF(pt); }
dan
Ah! I didn't know about this `implict operator`. That's what I was looking for! Thanks.
Mark
+1  A: 

Have you considered the option of writing an 'extension method' instead of rolling out your own class ?

You can't have operator overloading per se via extn. methods (proposed in next revision of the framework).. but you should be able to use a synonymous method called Add() for + and get by.

Gishu
Yes, I have considered it, but you can't write extensions for operators.
Mark
I just edited my answer before I saw your comment :) - See post above.
Gishu
Sure... but I want the syntactic sugar! Besides, I'm going to need this new class later, because I'm working with a 2nd library that also defines its own Point class... this will sort of merge them in some fashion.
Mark
+1  A: 

This compiles for me:

class PointF {
 float x; float y;
 public PointF(float x, float y)
 {
     this.x = x;
     this.y = y;
 }

 public PointF(System.Drawing.PointF p) : this(p.X, p.Y) { }
 public PointF(System.Drawing.Point p) : this(p.X, p.Y) { }

 public static implicit operator PointF(System.Drawing.Point pt) { return new PointF(pt); }
 public static implicit operator PointF(System.Drawing.PointF pt) { return new PointF(pt); }
}
//....
static void test(pointf.PointF p) {
}
//....
test(new System.Drawing.PointF(1, 1));
Igor Zevaka