C# Intermediate for Confirmed Developers: LINQ, Async, Generics
Intermediate C# for confirmed developers: value and reference types, records, generics, delegates, LINQ, async/await, pattern matching and dependency injection, with quizzes.
Study this lesson with its quizzes on Brainbotox →
Value types, reference types, structs and records in C#
A value type variable holds its data directly, while a reference type variable holds a reference to an object on the managed heap. This difference decides what happens on assignment, comparison and method calls.
The two families
| Value types | Reference types | |
|---|---|---|
| Examples | int, double, bool, DateTime, enum, struct | class, string, arrays, delegates, record (class) |
| Assignment | Copies the whole value | Copies the reference: both variables see the same object |
| Can be null | Only as T? (Nullable<T>) | Yes |
| Default equality | Compares the content | Compares the references |
struct PointS { public int X; }
class PointC { public int X; }
var s1 = new PointS { X = 1 }; var s2 = s1; s2.X = 9;
var c1 = new PointC { X = 1 }; var c2 = c1; c2.X = 9;
Console.WriteLine(s1.X); // 1 (s2 was a copy)
Console.WriteLine(c1.X); // 9 (c1 and c2 are the same object)Boxing
Converting a value type to object or to an interface boxes it: the value is copied into a new heap object. Unboxing copies it back. Boxing allocates memory, so avoid it in hot paths (this is one reason to use List<int> and not the old ArrayList).
int n = 42; object o = n; // boxing int m = (int)o; // unboxing
When to write a struct
Choose a struct for a small, immutable value with no identity (a coordinate, a money amount). A struct cannot inherit from another struct or class, but it can implement interfaces. Mark it readonly struct when it never changes.
Records: data with value equality
public record Person(string Name, int Age);
var a = new Person("Ada", 36);
var b = new Person("Ada", 36);
Console.WriteLine(a == b); // True: compares the values
var older = a with { Age = 37 }; // copy with one change
Console.WriteLine(a); // Person { Name = Ada, Age = 36 }record is a reference type (a record struct is a value type) for which the compiler generates value-based Equals, GetHashCode, ToString and with support. Positional records have init-only properties, so they are immutable by default.Equality for ordinary classes
For a class, == and Equals compare references unless you override them. If you override Equals, also override GetHashCode, otherwise Dictionary and HashSet misbehave. string is a reference type that already compares by content.
Nullable reference types
string name = null; // warning: non-nullable string? nick = null; // fine: declared nullable int len = nick!.Length; // ! silences the warning, and can still crash
NullReferenceException is still possible.Check yourself
- After var c2 = c1; where c1 is an instance of a class, what do c1 and c2 refer to?
- Which of these are value types in C#?
- What is boxing?
- Given public record Person(string Name, int Age); what does new Person("Ada", 36) == new Person("Ada", 36) return?
- What does the with expression do on a record?
- A struct can inherit from another struct.
- If you override Equals in a class, what else should you override?
- Enabling nullable reference types guarantees that NullReferenceException cannot occur at run time.
C# generics, constraints and collection interfaces
Generics let you write a class or method once and use it with any type, with full type safety and no boxing. List<T> and Dictionary<TKey, TValue> are generic types.
Generic classes and methods
public class Box<T>
{
public T Value { get; }
public Box(T value) => Value = value;
}
public static T Max<T>(T a, T b) where T : IComparable<T>
=> a.CompareTo(b) >= 0 ? a : b;
var box = new Box<int>(5);
int m = Max(3, 7); // T inferred as intConstraints
A constraint tells the compiler what T can do, so you can call those members.
| Constraint | Meaning |
|---|---|
where T : class | T is a reference type |
where T : struct | T is a non-nullable value type |
where T : new() | T has a public parameterless constructor |
where T : BaseType | T is or derives from BaseType |
where T : IInterface | T implements the interface |
where T : notnull | T is a non-nullable type |
The collection interfaces
| Interface | Adds |
|---|---|
IEnumerable<T> | Iteration with foreach, nothing more |
ICollection<T> | Count, Add, Remove |
IList<T> | Access by index |
IReadOnlyList<T> | Index and Count, no modification |
IDictionary<TKey, TValue> | Key to value lookup |
IEnumerable<T>, IReadOnlyList<T>), and return a precise one. This keeps callers free to pass an array, a list or a query.Picking a collection
| Type | Good for | Lookup |
|---|---|---|
List<T> | Ordered items, access by index | O(1) by index, O(n) by value |
Dictionary<TKey, TValue> | Find a value by key | O(1) on average |
HashSet<T> | Unique items, fast Contains | O(1) on average |
Queue<T> | First in, first out | |
Stack<T> | Last in, first out |
Iterators with yield return
static IEnumerable<int> Evens(int max)
{
for (int i = 0; i <= max; i += 2)
yield return i; // produces one value, then pauses
}
foreach (int n in Evens(1_000_000))
{
if (n > 6) break; // only 0, 2, 4, 6, 8 were ever computed
}MoveNext, not at the call.Check yourself
- What is the main benefit of generics in C#?
- What does the constraint where T : new() require?
- Which interface provides only iteration with foreach?
- Which collection gives average O(1) Contains checks and stores unique items?
- When does the body of a method using yield return start executing?
- Which collection is first in, first out?
- where T : struct allows T to be string.
- Which parameter type is the most flexible for a method that only loops over its input?
C# delegates, lambda expressions and events
A delegate is a type that holds a reference to a method, so that code can be passed around like data. Lambdas are a short way to write the method, and events are delegates exposed safely for notifications.
Delegates
public delegate int Operation(int a, int b); static int Add(int a, int b) => a + b; Operation op = Add; int r = op(2, 3); // 5
Func, Action and Predicate
You rarely declare your own delegate types. The library provides generic ones:
| Type | Signature |
|---|---|
Action<T> | Takes parameters, returns nothing |
Func<T, TResult> | Takes parameters, returns a value (the last type argument is the return type) |
Predicate<T> | Takes a T, returns bool |
Lambda expressions
Func<int, int, int> add = (a, b) => a + b; Action<string> log = msg => Console.WriteLine(msg); Func<int, bool> isEven = n => n % 2 == 0; var evens = numbers.Where(n => n % 2 == 0);
Closures
A lambda can use variables of the method around it. It captures the variable itself, not its value at that moment:
int factor = 2; Func<int, int> times = x => x * factor; factor = 10; Console.WriteLine(times(3)); // 30, not 6
for loop, every lambda captures the same loop variable, so all of them see its final value. Copy it into a local variable inside the loop. A foreach variable is fresh on each iteration, so it is safe.Multicast delegates
A delegate can hold several methods. += adds one, -= removes one, and invoking the delegate calls them in order. For a delegate with a return value, you get the result of the last method.
Events
public class Order
{
public event EventHandler<decimal>? Paid;
public void Pay(decimal amount)
{
Paid?.Invoke(this, amount); // null when nobody subscribed
}
}
var order = new Order();
order.Paid += (sender, amount) => Console.WriteLine($"Paid {amount}");
order.Pay(50m);event is a delegate field with restricted access: outside code can only subscribe (+=) and unsubscribe (-=). Only the declaring class can raise it or replace it.Events and memory leaks
The publisher holds a reference to every subscriber. If a long-lived publisher (a static event, a singleton service) keeps a subscription to a short-lived object, that object can never be garbage collected. Unsubscribe with -= when the subscriber is done.
Check yourself
- What is a delegate in C#?
- In Func<int, string, bool>, what is the return type?
- Which delegate type fits a method that takes a string and returns nothing?
- int factor = 2; Func<int,int> f = x => x * factor; factor = 10; What does f(3) return?
- What can code outside a class do with a public event of that class?
- Why write Paid?.Invoke(this, amount) and not Paid(this, amount)?
- Forgetting to unsubscribe from an event on a long-lived object can keep the subscriber alive in memory.
- What happens when a multicast delegate with three methods is invoked?
LINQ in C#: queries, deferred execution and IQueryable
LINQ (Language Integrated Query) is a set of extension methods that filter, transform, sort and group any sequence with the same syntax, whether the data is in memory, in a database or in XML.
Method syntax and query syntax
var adults = people
.Where(p => p.Age >= 18)
.OrderBy(p => p.Name)
.Select(p => p.Name);
var same = from p in people
where p.Age >= 18
orderby p.Name
select p.Name;Both compile to the same calls. Method syntax is the more common one.
The operators you use every day
| Operator | Purpose |
|---|---|
Where | Filter |
Select | Transform each item (projection) |
SelectMany | Flatten a sequence of sequences |
OrderBy, ThenBy | Sort |
GroupBy | Group items by a key |
Join | Match items of two sequences on a key |
Any, All, Contains | Tests that return bool |
Count, Sum, Min, Max, Average | Aggregates |
Distinct, Skip, Take | Remove duplicates, paging |
ToList, ToArray, ToDictionary | Run the query and store the result |
First, Single and their OrDefault forms
| Method | Empty sequence | More than one match |
|---|---|---|
First() | Throws | Returns the first |
FirstOrDefault() | Returns default (null, 0) | Returns the first |
Single() | Throws | Throws |
SingleOrDefault() | Returns default | Throws |
Deferred execution
foreach, ToList(), Count(), First()), and it runs again each time you enumerate it.var numbers = new List<int> { 1, 2, 3 };
var big = numbers.Where(n => n > 1); // nothing runs yet
numbers.Add(4);
Console.WriteLine(big.Count()); // 3: sees 2, 3 and 4ToList() once and reuse the list.GroupBy example
var byCity = people
.GroupBy(p => p.City)
.Select(g => new { City = g.Key, Count = g.Count(), AvgAge = g.Average(p => p.Age) });IEnumerable versus IQueryable
IEnumerable<T> | IQueryable<T> | |
|---|---|---|
| Runs | In memory, in your process | At the data source (for example SQL) |
| Lambdas are | Compiled delegates (Func) | Expression trees, translated by a provider such as EF Core |
// Filter runs in SQL: only matching rows are loaded var a = db.Orders.Where(o => o.Total > 100).ToList(); // AsEnumerable switches to memory: the WHOLE table is loaded first var b = db.Orders.AsEnumerable().Where(o => o.Total > 100).ToList();
IQueryable until filtering, sorting and paging are expressed, then materialise it.Check yourself
- When does a LINQ query such as numbers.Where(n => n > 1) actually execute?
- What does First() do on an empty sequence?
- What does Single() do when two elements match?
- Which operator flattens a list of lists into one sequence?
- A list holds 1, 2, 3. You write var q = list.Where(n => n > 1); then add 4 to the list. What is q.Count()?
- What is the key difference between IQueryable<T> and IEnumerable<T> with a database?
- Enumerating the same deferred LINQ query twice executes it twice.
- Which method is the efficient way to test whether a sequence has at least one element matching a condition?
Async and await in C#: Task-based asynchronous programming
async and await let a method wait for a slow operation without blocking a thread. While a web request or a database query is in progress, the thread is released to do other work.
The basic shape
public async Task<string> DownloadAsync(string url)
{
using var client = new HttpClient();
string body = await client.GetStringAsync(url); // thread is free while waiting
return body.ToUpper();
}| Return type | Use for |
|---|---|
Task | An async method with no result |
Task<T> | An async method that returns a T |
async void | Event handlers only |
await does not create a thread. It registers the rest of the method as a continuation and returns to the caller. When the operation completes, the method resumes.I/O-bound versus CPU-bound work
- I/O-bound (network, disk, database): await the async API directly. No thread is used while waiting.
- CPU-bound (heavy calculation): use
await Task.Run(() => Compute())to move the work to a thread pool thread and keep a UI responsive.
Running operations concurrently
// Sequential: about 2 seconds var a = await GetAAsync(); var b = await GetBAsync(); // Concurrent: about 1 second Task<int> ta = GetAAsync(); Task<int> tb = GetBAsync(); int[] results = await Task.WhenAll(ta, tb);
Task.WhenAll completes when all tasks finish. Task.WhenAny completes when the first one does.
The classic mistakes
.Result, .Wait() or .GetAwaiter().GetResult() blocks a thread, and in a UI or classic ASP.NET application it can deadlock. Use await all the way up the call chain.async void methods cannot be awaited, and an exception thrown in one cannot be caught by the caller: it can crash the process. Return Task.Exceptions
An exception thrown in an async method is stored in the returned Task and thrown again where the task is awaited, so ordinary try/catch around await works.
Cancellation
public async Task<string> LoadAsync(CancellationToken ct)
{
var response = await _http.GetAsync(url, ct); // pass the token down
ct.ThrowIfCancellationRequested();
return await response.Content.ReadAsStringAsync(ct);
}
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await LoadAsync(cts.Token); // throws OperationCanceledException after 5 sCancellation is cooperative: the caller requests it through a CancellationTokenSource, and the running code must check the token or pass it to the APIs it calls.
Async and accept a CancellationToken as the last parameter.Check yourself
- What does await do when the awaited operation has not finished yet?
- Which return type should an async method with no result normally use?
- Why is async void dangerous outside event handlers?
- Which call runs two independent async operations concurrently and waits for both?
- What is the risk of calling .Result on an incomplete Task?
- For a heavy CPU-bound calculation in a desktop app, what keeps the UI responsive?
- Cancellation with CancellationToken forcibly kills the running thread.
- Where is an exception thrown inside an async Task method observed?
Pattern matching, IDisposable and dependency injection in C#
Three tools mark the step from beginner to confirmed C# developer: pattern matching to test the shape of data, IDisposable to release resources, and dependency injection to assemble loosely coupled classes.
Pattern matching
// Type pattern with a variable
if (shape is Circle c)
Console.WriteLine(c.Radius);
// Null check
if (name is not null) { ... }
// Property pattern
if (order is { Status: "Paid", Total: > 100 }) { ... }Switch expressions
decimal Discount(Customer c) => c switch
{
{ IsVip: true } => 0.20m,
{ Orders: >= 10 } => 0.10m,
{ Orders: > 0 and < 10 } => 0.05m,
_ => 0m
};
double Area(Shape s) => s switch
{
Circle c => Math.PI * c.Radius * c.Radius,
Rectangle r => r.Width * r.Height,
_ => throw new ArgumentException("Unknown shape")
};SwitchExpressionException.IDisposable and using
The garbage collector frees memory, but it knows nothing about files, sockets or database connections. A type that owns such a resource implements IDisposable, and callers release it deterministically with using.
using var conn = new SqlConnection(cs); // Dispose() at end of scope await using var stream = File.OpenRead(p); // DisposeAsync() for IAsyncDisposable
new HttpClient() per request and dispose it: this exhausts sockets under load. Reuse one instance or use IHttpClientFactory.Dependency injection (DI)
With DI, a class receives the objects it needs through its constructor instead of creating them. It depends on an interface, so the implementation can be swapped, for example with a fake in a unit test.
public interface IEmailSender { Task SendAsync(string to, string body); }
public class OrderService
{
private readonly IEmailSender _email;
public OrderService(IEmailSender email) => _email = email; // constructor injection
}
// Program.cs
builder.Services.AddScoped<IEmailSender, SmtpEmailSender>();
builder.Services.AddScoped<OrderService>();Service lifetimes
| Lifetime | A new instance is created | Typical use |
|---|---|---|
Transient | Every time it is requested | Light, stateless services |
Scoped | Once per scope (per HTTP request in ASP.NET Core) | DbContext, per-request state |
Singleton | Once for the whole application | Caches, configuration; must be thread-safe |
IDisposable services it creates, at the end of their scope. Do not dispose injected services yourself.Check yourself
- What does if (shape is Circle c) do?
- In what order are the arms of a switch expression evaluated?
- Why does IDisposable exist when .NET has a garbage collector?
- In ASP.NET Core, how often is a Scoped service created?
- Which lifetime is the usual choice for an EF Core DbContext?
- What is a captive dependency?
- What is the main benefit of constructor injection against an interface?
- A Singleton service used by concurrent requests must be thread-safe.