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.
1
2
3
4
5
6
7
8
9
10
11
12
| // 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.
1
| Point3D first = new Point3D(1.0f, 2.0f, 3.3f, "Floyd" ); |