#108 – Defining a Constructor for a Struct

Every struct includes a default (parameterless) constructor that you can’t override.  However, you can define a constructor that takes one or more parameters, typically used to initialize the struct’s fields.  The method name for the constructor is always identical to the name of the struct itself.

 // A 3D point with a name
 public struct Point3D
 {
     public float X, Y, Z;
     public string Name;

     public Point3D(float x, float y, float z, string name)
     {
         X = x; Y = y; Z = z;
         Name = name;
     }
 }

You can now declare a variable of the struct type and use the new operator to invoke the constructor, passing it values that will be used to initialize the instance of the struct.

 Point3D first = new Point3D(1.0f, 2.0f, 3.3f, "Floyd");

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment