Classes and Objects
C# classes and objects work like Java's with additional ergonomics: object initialiser syntax, primary constructors (C# 12), and records for immutable data.
public class Learner {
public string Name;
public int Age;
public string Course;
public void Introduce() =>
Console.WriteLine($"I am {Name}, aged {Age}, studying {Course} at Your IT Tutor.");
public string GradeLabel() => Mark switch {
>= 80 => "Distinction",
>= 60 => "Merit",
>= 50 => "Pass",
_ => "Not yet competent"
};
public double Mark { get; set; } // auto-property
}
Object Initialiser Syntax
C# lets you set public properties and fields inline at construction — no need for a matching constructor overload.
// Standard construction then assignment:
var l1 = new Learner();
l1.Name = "Thandi";
l1.Age = 21;
l1.Course = "C#";
l1.Mark = 74.5;
// Object initialiser — same result, much cleaner:
var l2 = new Learner { Name = "Sipho", Age = 24, Course = "Java", Mark = 81.0 };
l1.Introduce();
l2.Introduce();
Console.WriteLine(l2.GradeLabel()); // Merit
Records — Immutable Data Classes
Records are a concise way to define immutable data types. The compiler generates constructor, properties, equality, ToString, and deconstruct automatically.
// One line replaces 30 lines of boilerplate:
record Learner(string Name, int Age, string Course, double Mark);
var l1 = new Learner("Thandi", 21, "C#", 74.5);
var l2 = new Learner("Thandi", 21, "C#", 74.5);
Console.WriteLine(l1); // Learner { Name = Thandi, ... }
Console.WriteLine(l1 == l2); // True — records compare by value
// with expression — create a modified copy:
var l3 = l1 with { Mark = 82.0 };
Console.WriteLine(l3);
Practice Task
Your Turn
Create a Product class with Name, Price (decimal), Category (string), InStock (bool). Use object initialiser to create 3 products. Create a ProductRecord record with the same fields. Create one record instance and show that value equality works (two records with identical data are equal).
Common Mistakes
- Public fields are fine here but real code uses Properties (Lesson 12).
- Forgetting
new. - C# method names are PascalCase.
- Records are immutable — use
withto create modified copies.
Professional Tip
Use records for data transfer objects, value objects, and configuration — anything that is fundamentally 'data with no behaviour'. Use regular classes when the object has mutable state and behaviour.
Mini Quiz
What does C# object initialiser syntax allow?