#298 – A struct Can Have Several Constructors
April 11, 2011 Leave a comment
You can define more than one constructor for a struct, as long as the method signature for each constructor is different.
public struct Point3D
{
public double x;
public double y;
public double z;
public Point3D(double xi, double yi, double zi)
{
x = xi;
y = yi;
z = zi;
}
public Point3D(int n)
{
x = n;
y = n;
z = n;
}
}
Now you can instantiate a variable of this type in several different ways.
Point3D pt1 = new Point3D(); // Default parameterless constructor
Point3D pt2 = new Point3D(10.0, 20.0, 30.0);
Point3D pt3 = new Point3D(5);