Lesson 11/30

Tutorials C# Mastery

Mastering Primary Constructors & Object Initializers

On this page

Primary Constructors & Object Initializers

In C# 12, Microsoft introduced Primary Constructors for classes and structs, effectively making code cleaner and reducing the amount of redundant "assigning parameters to private fields" we’ve done for decades.

1. Eliminate Constructor Bloat

In legacy C#, 50% of your class was just boilerplate for Dependency Injection. Primary constructors allow you to define parameters directly on the class header.

❌ Legacy Injection
public class Service 
{
    private readonly IRepository _repo;
    public Service(IRepository repo) 
    {
        _repo = repo;
    }
}
✅ Modern C# 12 Style
// The parameter 'repo' is available throughout the whole class body!
public class Service(IRepository repo) 
{
    public async Task DoWork() => await repo.Save();
}

2. Required Properties & Object Initializers

Sometimes you don't want a constructor at all, but you want to FORCE the developer to set a property when they create the object. We use the required keyword.

public class User 
{
    public required string Email { get; init; }
    public string? OptionalNickName { get; set; }
}

// ❌ ERROR: Compiler yells because 'Email' was not set
var u = new User();

// ✅ GOOD
var u = new User { Email = "sandeep@example.com" };

4. Interview Mastery

Q: "If I use a Primary Constructor on a class, why can't I access the parameter from outside the class instance?"

Architect Answer: "Primary constructor parameters in classes are NOT properties or fields; they are purely parameters with a 'Class-wide' scope. The compiler captures them privately. If you want a primary constructor parameter to be publicly visible, you must manually assign it to a public property inside the class body. This is a deliberate security feature to avoid 'accidental exposure' of injected services (`DbContext`, `Logger`) which should remain private internal implementation details."

C# Mastery
Course syllabus
1. Modern C# & Framework Fundamentals Introduction to the .NET Ecosystem & Runtime (JIT, CLR) C# 12/13 Top-Level Statements & Global Usings Variables, Data Types, and Value vs Reference Deep Dive Mastering Nullable Reference Types & Null Safety The Magic of Strings (Interpolation, Verbatim, and Immutability)
2. Control Flow & Logical Structures Advanced Pattern Matching (Switch Expressions) The Precision of Numbers: Checked vs Unchecked Math Iterators: Foreach, Yield Return, and Deferred Execution Defensive Programming: Guard Clauses and Exception Mastery
3. Object-Oriented Mastery Classes vs Structs vs Records (Which to use when?) Mastering Primary Constructors & Object Initializers Interface Architectures: Default Implementations & Segregation Polymorphism vs Composition (The Architect's Dilemma) Partial Classes, Extension Methods, and Static Classes
4. Functional C# & Collections Delegates, Func, Action, and Predicates Lambda Expressions & The Evolution of Linq Dynamic Array Management: List<T>, Dictionary, and HashSet Custom Collections & Yielding Data streams
5. Asynchronous & Parallel Programming Async/Await Deep Dive: Task Lifecycle & Thread Safety Synchronization Context & Avoiding Deadlocks Parallel.ForEach vs PLINQ vs Tasks CancellationToken Mastery: Surgically Aborting Operations
6. Advanced Engineering & High Performance Generics & Constraints: Building Type-Safe Libraries Reflection and Attributes: Reading Metadata at Runtime Dependency Injection Internals (ServiceCollection from scratch) High-Performance Memory: Span<T> and ReadOnlySpan<T> Garbage Collection Segments & LOH Internals Managing Unmanaged Resources: IDisposable & Finalizers Introduction to Source Generators & Interceptors C# Interview Masterclass: Architect-Level Explanations
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details