C# Classes & Objects

Fields, properties and constructors.

✍️ 2 exercises in this lesson
  • A class defines fields, properties and methods.
  • Auto-properties: public string Name { get; set; }
  • init properties can only be set when the object is created.
  • Constructors share the class name; primary constructors (C# 12) put parameters on the class itself.
  • record types are concise immutable data classes.

Key Takeaways: C# Classes & Objects

Mastering C# Classes & Objects helps you write clean and reliable C# code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

C# Classes & Objects Code Example

C#
var acc = new Account("Ayesha");
acc.Deposit(5000);
acc.Deposit(1500);
Console.WriteLine($"{acc.Owner}: {acc.Balance}");

var p = new Product("Laptop", 185000m);
Console.WriteLine(p);
Console.WriteLine(p with { Price = 175000m });

class Account
{
    public string Owner { get; }
    public decimal Balance { get; private set; }

    public Account(string owner) => Owner = owner;

    public void Deposit(decimal amount)
    {
        if (amount <= 0) throw new ArgumentException("Amount must be positive");
        Balance += amount;
    }
}

record Product(string Name, decimal Price);
Output
Ayesha: 6500
Product { Name = Laptop, Price = 185000 }
Product { Name = Laptop, Price = 175000 }
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

C# Classes & Objects Practice Exercises

Check what you learned in “C# Classes & Objects”.

/ 2 solved
Fill in the blank

Declare an auto-property with a getter only.

public string Owner { ; }
✓ Correct! Not quite. Try again.
Multiple choice

What is a record in C#?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services