#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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: