0Pricing
C# Academy · Lesson

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)); // 15

Capture 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());  // 9

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