🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

C# Constructors, Object Initializers, and Records — Complete Beginner Guide

C# FundamentalsConstructors and Records🟢 Free Lesson

C# Constructors, Object Initializers, and Records — Complete Beginner Guide

Learning Objectives

  • Create constructors that set up objects
  • Overload constructors for flexible creation
  • Use object initializer syntax
  • Understand the role of records
  • Choose the right creation style for a task

What Is a Constructor

A constructor runs when you create an object. Its job is to leave the object in a valid state.

class Player
{
    string name;
    int level;

    public Player(string playerName, int startLevel)
    {
        name = playerName;
        level = startLevel;
    }
}

Player p = new Player("Ash", 1);
Console.WriteLine(p.name);

The constructor name matches the class name and has no return type.

Default Constructors

If you write no constructor, the compiler adds a parameterless one for simple classes. As soon as you define your own constructor, that automatic default disappears unless you also declare it.

class Empty
{
    public Empty()
    {
        Console.WriteLine("Created");
    }
}

Empty e = new Empty();

Constructor Overloading

Multiple constructors let callers choose how much information to provide.

class Product
{
    string name;
    double price;

    public Product(string name)
    {
        this.name = name;
        price = 0;
    }

    public Product(string name, double price)
    {
        this.name = name;
        this.price = price;
    }
}

Product a = new Product("Keyboard");
Product b = new Product("Mouse", 499.5);

Use this to refer to the current object when parameter names overlap with fields.

Field Initialization

You can give fields default values before the constructor body runs.

class Session
{
    int hits = 1;
    bool active = true;

    public Session()
    {
    }
}

Session s = new Session();

Initializers run first, then the constructor body can adjust further.

Object Initializers

Object initializer syntax sets accessible properties right after new.

class Book
{
    public string Title { get; set; }
    public double Price { get; set; }
}

Book book = new Book
{
    Title = "Clean Code",
    Price = 350.0
};

Console.WriteLine(book.Title);

This style is excellent when a type has settable properties and no required constructor arguments.

Combining constructor and initializer

class Ticket
{
    public string EventName { get; }
    public string Seat { get; set; }

    public Ticket(string eventName)
    {
        EventName = eventName;
    }
}

Ticket t = new Ticket("Concert")
{
    Seat = "A12"
};

Console.WriteLine(t.EventName);
Console.WriteLine(t.Seat);

Collection Initializers

List<int> nums = new List<int> { 1, 2, 3, 4 };

foreach (int n in nums)
{
    Console.WriteLine(n);
}

Initializer syntax seeds the collection in one line so setup code stays short.

Introduction to Records

Records are reference types designed for immutable or mostly immutable data. They shine for plain data carriers and value based equality.

record Person(string Name, int Age);

Person a = new Person("Sam", 30);
Person b = new Person("Sam", 30);

Console.WriteLine(a == b);
Console.WriteLine(a);

With positional records, the compiler creates a constructor and read only properties for you.

Traditional record body style

record Invoice
{
    public string Id { get; init; }
    public double Total { get; init; }
}

Invoice inv = new Invoice { Id = "A1", Total = 99.5 };
Console.WriteLine(inv.Id);

init accessors allow setting only during object creation, which supports initializers while protecting data later.

Class vs Record

Featureclassrecord
Typical useBehavior rich objectsData focused values
Equality defaultReference equalityValue style equality
MutabilityFlexibleOften init only
InheritanceTraditionalSupported, mainly sealed style

Use records for DTOs, query results, and configuration snapshots. Use classes when objects own complex behavior and long lived state.

Common Mistakes

Forgetting required constructor data

If a constructor demands arguments, callers must supply them. Consider overloads or defaults for optional data.

Mutating records freely

Records often use init only properties. Plan values at creation time instead of editing later.

Overusing initializers for logic

If setting a property needs validation or related work, prefer a method or constructor that expresses the rule.

Key Takeaways

💡

  • Constructors initialize objects at creation time
  • Overloads offer multiple creation paths for the same class
  • Object initializers set properties cleanly after new
  • Records fit immutable data with value based equality
  • Use this to disambiguate parameter and field names

Practice Questions

  1. When does a constructor run?
  2. What happens to the implicit default constructor after you add your own?
  3. What benefit does object initializer syntax provide?
  4. What kind of members does a positional record generate?
  5. Design a record for a book with title and price, then print one instance.

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert C# Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement