ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)
Set your Publisher ID in src/config/ads.ts to display live ads.
C# Tutorial• 7 min read
Classes, Properties & Records
Auto-properties { get; set; }, primary constructors, and immutable record types
C# combines traditional Object-Oriented classes with modern immutable record types designed for clean data modeling.
Classes vs Records
Auto-Properties: public string Title { get; set; } eliminates manual backing fields.
init accessor: Allows properties to be set during object initialization only, enforcing immutability thereafter.
record: A lightweight reference type with built-in value-based equality and non-destructive mutation via with expressions.
C# 12 Primary Constructors and Records
// One-line immutable record with value-based equality!
public record Course(string Title, int LessonCount, string Level);
public class Program {
public static void Main() {
var c1 = new Course("C# Cloud Architecture", 10, "Advanced");
Console.WriteLine(c1);
// Non-destructive mutation with 'with' expression
var c2 = c1 with { Level = "Master" };
Console.WriteLine(c2);
// Value equality (checks properties, not memory address!)
Console.WriteLine(c1 == c2); // False
}
}ADVERTISEMENT
Google AdSense Slot (inContentBanner)
Set your Publisher ID in src/config/ads.ts to display live ads.
Test Yourself With Exercise
What expression in C# creates an immutable copy of a `record` with specific modified properties?