dima618
dima618

Reputation: 87

C# Constructor breaks due to another constructor

I have a C# point class with multiple constructors in a library (This is a different class than a System.Drawing.Point in .NET).

Public class Point {

   public float X;
   public float Y;
   public float Z;

   //Constructor 1
   public Point(float x, float y, float z) {
      this.X = x;
      this.Y = y;
      this.Z = z;
   }
   //Constructor 2
   public Point(Point point) {
      this.X = point.X;
      this.Y = point.Y;
      this.Z = point.Z;
   }
   //Constructor 3
   public Point(PointF point) {
      this.X = point.X;
      this.Y = point.Y;
      this.Z = 0;
   }
   //Constructor 4
   public Point(System.Drawing.Point point) {
      this.X = point.X;
      this.Y = point.Y;
      this.Z = 0;
   }
}

When I am trying to create a new Point object using the constructor that takes in float as parameters, everything works fine. When I want to create a new Point using an existing Point object (Constructor 2), I receive an error saying that I need to reference the System.Drawing assembly. I am guessing this is because of constructors 3 and 4 since they take a System.Drawing.Point and a PointF as an argument, but I don't see why they should pose an issue, since the constructor I am trying to use is completely unrelated to them, and constructor 1 works fine when called. How do I get around this issue? Thanks!

Upvotes: 1

Views: 104

Answers (1)

Matthew Watson
Matthew Watson

Reputation: 109547

There is a workaround for this, if you can accept it.

Add the following to your Point class:

public static Point Clone(Point p)
{
    return new Point(p);
}

Then in the code that is currently failing to compile, do this instead:

Point p = new Point(0, 0, 0);
Point q = Point.Clone(p);

(Of course, you don't have to call the method Clone() - call it Copy or CopyCtor or whatever you like.)

As to why the compiler insists that you must include a reference to an assembly defining types that you're not even using, see this answer.

Also see this question.

Upvotes: 1

Related Questions