Part 1: The big picture Lesson 5 of 5 in this part
C# in a nutshell (for Python developers)
What you will learn. Read and write the small amount of C# that the lessons use (records, LINQ grouping, generic methods, async tasks and spans), by comparing each idea with the Python you already know.
Before this lesson: nothing. You can start here.
In plain words
This is an optional refresher for people who know Python and are new to C#. C# is a typed language: every value has a type that is checked before the program runs, so many mistakes are caught early. Code is grouped by braces and every statement ends with a semicolon. A record is a small, unchangeable data holder, like a Python dataclass. LINQ is a set of methods such as Where, Select and GroupBy that work on lists, much like comprehensions. A generic method works for any type that meets a stated rule. async and await let a program wait for slow work, such as a web request, without blocking. A Span is a window onto memory that avoids copying, like a slice in Python.
C#
- record
- LINQ GroupBy
- async and await
Python
- dataclass
- setdefault or a loop
- async and await
Most C# in this guide maps to a Python idea you already use.
- InputWrite the code in Program.csTypes and braces
- ProcessBuild with dotnet buildThe compiler checks every type
- ModelRun with dotnet runRuns the compiled program
- OutputRead the printed outputSame result as the Python version
The compiler checks the types first. Type errors stop the build, not the run.
- ProcessRecords and groupingData holder plus GroupBy
- ModelGeneric methodsOne method for many types
- RiskAsync tasksWait without blocking
- InputSpansA window, no copy
Each task is small, and each is a pattern that appears again in the lessons.
Real-world example
A team's model runs in Python, but the company's web service is written in C#. A developer who knows Python needs to read the service code that calls the model. It stores each request in a record, groups requests by customer with LINQ, calls the model through an async method so the page stays responsive, and passes a slice of an array without copying it. These four ideas are most of what the C# examples in this guide use.
How it works
- Types.
int,stringanddoubleare checked when you build.varlets the compiler work the type out, but it is still fixed. - Records.
record Student(string Name, string Class, int Mark);makes a small immutable class with the three fields. - LINQ.
students.GroupBy(s => s.Class)groups by class, thenCount()andAverage(...)summarise each group. The arrows => ...is a small function. - Generics.
T Largest<T>(IEnumerable<T> items) where T : IComparable<T>works for numbers and words alike, because both can be compared. - Async.
async Task<int>marks a method that can wait.await Task.WhenAll(...)runs several at once and collects the results. - Span.
data[1..4]is a window onto items 1, 2 and 3 of the same memory.
Python example
Python: example run The example programme behind this lesson's quoted output ran on 2026-11-19 (Python 3.12.10). 1 code block in the lesson passed a syntax check, 1 also ran on their own.
The Python equivalent of the four tasks: a dataclass, grouping with a dictionary, a comparison-based function, asyncio and a slice.
"""The Python equivalent of the C# refresher: records, grouping, generics, async and slices.
Run: python refresher_csharp.py
"""
import asyncio
from dataclasses import dataclass
@dataclass(frozen=True)
class Student: # like a C# record: a small data holder
name: str
cls: str
mark: int
students = [Student("Ana", "A", 70), Student("Ben", "A", 85), Student("Cy", "B", 90), Student("Di", "B", 60), Student("Eve", "B", 75)]
groups = {}
for s in students: # like LINQ GroupBy
groups.setdefault(s.cls, []).append(s.mark)
for key in sorted(groups):
marks = groups[key]
print("class %s: %d students, average %.1f" % (key, len(marks), sum(marks) / len(marks)))
def largest(items): # works for anything that can be compared
best = items[0]
for item in items[1:]:
if item > best:
best = item
return best
print("largest number: %d, largest word: %s" % (largest([4, 9, 2]), largest(["pear", "apple", "zebra"])))
async def slow_double(x): # like an async method
await asyncio.sleep(0.01)
return 2 * x
async def main():
return await asyncio.gather(*[slow_double(x) for x in (1, 2, 3)])
doubled = asyncio.run(main())
print("doubled in parallel: [%s] total %d" % (", ".join(map(str, doubled)), sum(doubled)))
data = [1, 2, 3, 4, 5]
print("sum of the middle three:", sum(data[1:4])) # like a Span sliceclass A: 2 students, average 77.5
class B: 3 students, average 75.0
largest number: 9, largest word: zebra
doubled in parallel: [2, 4, 6] total 12
sum of the middle three: 9Class A has marks 70 and 85, so its average is 77.5. Class B has 90, 60 and 75, so its average is 75.0. The middle three of 1, 2, 3, 4, 5 are 2, 3 and 4, which add to 9.
.NET (C#) example
C#: compiled and run The C# sample compiled on 2026-11-19 with .NET SDK 10.0.400 (no extra packages). It also ran to the end without error.
The four tasks in C# with no packages. It prints the same output as the Python program above.
// C# in a nutshell for this guide: records, LINQ grouping, generics, async and Span.
var students = new List<Student> { new("Ana", "A", 70), new("Ben", "A", 85), new("Cy", "B", 90), new("Di", "B", 60), new("Eve", "B", 75) };
foreach (var g in students.GroupBy(s => s.Class).OrderBy(g => g.Key)) // LINQ GroupBy
Console.WriteLine($"class {g.Key}: {g.Count()} students, average {g.Average(s => s.Mark):F1}");
T Largest<T>(IEnumerable<T> items) where T : IComparable<T> // a generic method: works for anything comparable
{
T best = items.First();
foreach (var item in items.Skip(1)) if (item.CompareTo(best) > 0) best = item;
return best;
}
Console.WriteLine($"largest number: {Largest(new[] { 4, 9, 2 })}, largest word: {Largest(new[] { "pear", "apple", "zebra" })}");
async Task<int> SlowDouble(int x) { await Task.Delay(10); return 2 * x; } // an async method
var doubled = await Task.WhenAll(new[] { 1, 2, 3 }.Select(SlowDouble));
Console.WriteLine($"doubled in parallel: [{string.Join(", ", doubled)}] total {doubled.Sum()}");
Span<int> data = stackalloc int[] { 1, 2, 3, 4, 5 }; // a Span: a window onto memory with no copy
Span<int> middle = data[1..4];
int sum = 0; foreach (int v in middle) sum += v;
Console.WriteLine($"sum of the middle three: {sum}");
record Student(string Name, string Class, int Mark); // a record: a small immutable data holderMaths behind it
- None needed. The only calculations are averages and a sum.
Common mistakes
- Forgetting the semicolon at the end of a statement.
- Writing
awaitin a method that is not markedasync. - Using
==to compare text in a way that ignores the culture rules you wanted. Use an explicit comparer when it matters. - Dividing two integers and expecting a decimal.
5 / 2is 2 in C#, and5 / 2.0is 2.5. - Copying a large array when a
Spanwould do.
Quick check
What is the Python match for a C# record?
Show answer
A frozen dataclass: a small data holder whose fields cannot be changed.
What does
GroupByfollowed byAveragegive for class B with marks 90, 60 and 75?Show answer
75.0, because (90 + 60 + 75) รท 3 = 75.
Why do generic methods need a rule such as
IComparable<T>?Show answer
The method compares items, so the compiler must know that every type used can be compared.
What does
await Task.WhenAll(...)do?Show answer
It runs the tasks together, waits for all of them and returns their results as a list.
Completion
Evidence of completion. The refresher program run on your machine with the .NET SDK, plus the same four tasks written again by you in your own words and checked against the output.
Saved in this browser only. Reading and exercise are ticked separately because they are different achievements. A tick records your own work; it is not a test result. See all progress.