0Pricing
C# Academy · Lesson

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,4

A 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,0

All lessons in this course

  1. Primary Constructors on Classes
  2. Capturing Parameters in Members
  3. Primary Constructors with Structs
  4. Combining with Properties and Bases
← Back to C# Academy