Capturing Parameters in Members
Use primary constructor parameters throughout the type.
Using Parameters in Members
The power of primary constructors comes from using the parameters inside members: methods, properties, and field initializers. The compiler arranges storage as needed.
using System;
class Multiplier(int factor) {
public int Apply(int n) => n * factor;
}
Console.WriteLine(new Multiplier(3).Apply(5)); // 15Capture vs Initializer-Only
If a parameter is used only in a field/property initializer, no extra storage is needed. If it is used in a method, the compiler captures it into a hidden field.
using System;
class A(int x) {
public int Stored = x; // initializer only
}
class B(int x) {
public int Get() => x; // captured into a field
}
Console.WriteLine(new A(7).Stored); // 7
Console.WriteLine(new B(9).Get()); // 9All lessons in this course
- Primary Constructors on Classes
- Capturing Parameters in Members
- Primary Constructors with Structs
- Combining with Properties and Bases