0Pricing
C# Academy · Lesson

Primary Constructors on Classes

Declare constructor parameters in the type header.

What Is a Primary Constructor?

A primary constructor lets you declare constructor parameters directly in the class header, like class Point(int x, int y). The parameters are in scope throughout the whole class body.

using System;

class 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

No More Boilerplate

Before primary constructors you wrote a constructor body just to copy parameters into fields. Now the header declares the parameters and you reference them directly.

using System;

class Greeter(string name) {
    public string Greet() => "Hello, " + name + "!";
}

Console.WriteLine(new Greeter("Ada").Greet()); // Hello, Ada!

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