1

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!

dima618
  • 67
  • 11
  • 2
    Add a reference to System.Drawing? – Polyfun Jul 28 '20 at 16:32
  • You can't initialize one instance member using an other instance member – Jordan1993 Jul 28 '20 at 16:34
  • @Polyfun This object is in a library, and I don't want to require users to implement System.Drawing unnecessarily. – dima618 Jul 28 '20 at 16:50
  • 1
    @Jordan1993 What do you mean by that? In constructor 2 I am able to use the X, Y and Z values of the `Point` parameter to create a new `Point` with the same X, Y and Z values. – dima618 Jul 28 '20 at 16:58

1 Answers1

1

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.

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276