Loading lessons...
Modern C# Features
Modern C# Features
C# keeps evolving. These modern features make code shorter, safer, and more expressive.
Top-level statements
Skip the ceremony - just write the code:
Console.WriteLine("Hello, World!");
This is the whole file. The compiler generates the Main method for you.
Expression-bodied members
Short methods and properties with =>:
public int Square(int x) => x * x;
public string Name { get; set; } = "Ada";
Records
A record is a class designed for immutable data - value semantics and value equality come free:
record Person(string Name, int Age);
var p1 = new Person("Ada", 36);
var p2 = new Person("Ada", 36);
Console.WriteLine(p1 == p2); // True - value equality
Null-conditional operator
?. only calls the member if the object isn't null:
string? name = null;
Console.WriteLine(name?.ToUpper() ?? "empty"); // empty
string interpolation
You've seen quot;{x}" - it's the modern way to build strings.
switch expressions
An expression version of switch:
string DayName(int d) => d switch
{
1 => "Monday",
2 => "Tuesday",
_ => "Unknown"
};
TL;DR
- Top-level statements drop the boilerplate.
- Records give immutable, value-equal data.
?.safely handles nulls.- Switch expressions and interpolation keep code tidy.