Primary Constructors with Structs
Apply primary constructors to value types.
Primary Constructors on Structs
Structs support primary constructors too: struct Point(int x, int y). They work much like on classes, declaring parameters in the header.
using System;
struct Point(int x, int y) {
public int X => x;
public int Y => y;
}
var p = new Point(3, 4);
Console.WriteLine(p.X + "," + p.Y); // 3,4A Parameterless Constructor Still Exists
Structs always have an implicit parameterless constructor producing the default value. A primary constructor adds a parameterized one alongside it.
using System;
struct Vec(int x, int y) {
public int X => x;
public int Y => y;
}
var zero = new Vec(); // default: x=0, y=0
Console.WriteLine(zero.X + "," + zero.Y); // 0,0All lessons in this course
- Primary Constructors on Classes
- Capturing Parameters in Members
- Primary Constructors with Structs
- Combining with Properties and Bases