ECMA-334 C# Language Specification18.3.8: Constructors |
Unlike a class, a struct is not permitted to declare a parameterless instance constructor. Instead, every struct implicitly has a parameterless instance constructor, which always returns the value that results from setting all value type fields to their default value and all reference type fields to null (11.1.1). A struct can declare instance constructors having parameters.
struct Point
{
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
both create a Point with x and y initialized to zero. end example]
Point p1 = new Point();
Point p2 = new Point(0, 0);
A struct instance constructor is not permitted to include a constructor initializer of the form base(...).
The this variable of a struct instance constructor corresponds to an out parameter of the struct type, and similar to an out parameter, this must be definitely assigned (12.3) at every location where the constructor returns.
struct Point
{
int x, y;
public int X {
set { x = value; }
}
public int Y {
set { y = value; }
}
public Point(int x, int y) {
X = x; // error, this is not yet definitely assigned
Y = y; // error, this is not yet definitely assigned
}
}