#297 – Three Different Ways to Initialize the Contents of a struct

You must assign a value to each field in a struct before using it, but there are several different ways to do this.

The first way is to assign the values directly, after you declare a new struct variable.

            Point3D myPoint;
            myPoint.x = 34.0;
            myPoint.y = 25.0;
            myPoint.z = 36.0;

The second way to assign values to all of the fields is to invoke the parameterless constructor, by using the new operator.  Note that you always get the built-in parameterless constructor–you cannot declare your own parameterless constructor in a custom struct.

This built-in constructor will initialize all fields to their default values.

            Point3D myPoint = new Point3D();

The last way to assign values is to invoke a custom constructor, assuming that your constructor assigns values to the fields.

            Point3D myPoint = new Point3D(10.0, 20.0, 30.0);