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,4No 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
- Primary Constructors on Classes
- Capturing Parameters in Members
- Primary Constructors with Structs
- Combining with Properties and Bases