Merge Parameters and IList <T> Constructors

Is there a way to combine these two constructors into one? Basically they accept the same array of type Point3D .

 public Curve(int degree, params Point3D[] points) {} public Curve(int degree, IList<Point3D> points) {} 

Thanks.

+5
source share
3 answers

If I understand you correctly, the problem is that you cannot just do the following:

 public Curve(int degree, params Point3D[] points) : this(degree, points) //want to chain to (int, IList<Point3D>) constructor { } public Curve(int degree, IList<Point3D> points) { } 

Because you get the following compile-time error: Error CS0516 Constructor 'Curve.Curve(int, params int[])' cannot call itself".

You can get around this by simply linking to the appropriate type.

 public Curve(int degree, params Point3D[] points) : this(degree, (IList<Point3D>)points) { } 

This works because the array T[] implements IList<T> .

0
source

If you want to have 2 different constructors, you can:

 public Curve(int degree, params Point3D[] points) : this(degree, (IList<Point3D>)points) { } public Curve(int degree, IList<Point3D> points) { } 

Or, if you want only one constructor to be able to say the first, you can initialize like this:

 new Curve(0,new List<Point3D>().ToArray()); 

With one constructor calling another, you don’t need to duplicate all your logic, and you still include both initialization formats.


Although Array implements IList<T> , you cannot delete (IList<Point3D) due to a compilation error: compiler ...... cannot call itself

enter image description here

+4
source

If it looks like this:

 public Curve(int degree, Point3D[] points) { ... } public Curve(int degree, IList<Point3D> points) { ... } 

than you could use: (as long as you only need to iterate through the collection for the Point3D s contained in it)

 public Curve(int degree, IEnumerable<Point3D> points) { ... } 

However, since you want to have a params constructor, this cannot be done because you cannot call such a constructor:

 Curve curve = new Curve(30, p1, p2, p3); 

But just like that:

 Curve curve = new Curve(30, new Point3D[] {p1, p2, p3}); 

You can reuse your code using:

 public Curve(int degree, params Point3D[] points) { ... } public Curve(int degree, IList<Point3D> points) : this(degree, points.ToArray()) { } 

or vice versa:

 public Curve(int degree, IList<Point3D> points) { ... } public Curve(int degree, params Point3D[] points) : this(degree, points as IList<Point3D>) { } 

which initializes the instance using the params constructor the same way it uses List .

PS: You might want to consider changing IList to IEnumerable to allow the user of this class to use it more abstractly.

+1
source

All Articles