Brainbotox · Lessons · Exams

C# Intermediate for Confirmed Developers: LINQ, Async, Generics

by lazizanie · Programming · C# / .NET · English

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 typesReference types
Examplesint, double, bool, DateTime, enum, structclass, string, arrays, delegates, record (class)
AssignmentCopies the whole valueCopies the reference: both variables see the same object
Can be nullOnly as T? (Nullable<T>)Yes
Default equalityCompares the contentCompares 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)
"Value types live on the stack" is a simplification. A value type stored in a class field or an array lives on the heap, inside that 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 }
A 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
Nullable reference types are a compile-time check only. They produce warnings, not run-time protection: a NullReferenceException is still possible.

Check yourself

  1. After var c2 = c1; where c1 is an instance of a class, what do c1 and c2 refer to?
  2. Which of these are value types in C#?
  3. What is boxing?
  4. Given public record Person(string Name, int Age); what does new Person("Ada", 36) == new Person("Ada", 36) return?
  5. What does the with expression do on a record?
  6. A struct can inherit from another struct.
  7. If you override Equals in a class, what else should you override?
  8. Enabling nullable reference types guarantees that NullReferenceException cannot occur at run time.

Take the quiz on Brainbotox

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 int

Constraints

A constraint tells the compiler what T can do, so you can call those members.

ConstraintMeaning
where T : classT is a reference type
where T : structT is a non-nullable value type
where T : new()T has a public parameterless constructor
where T : BaseTypeT is or derives from BaseType
where T : IInterfaceT implements the interface
where T : notnullT is a non-nullable type

The collection interfaces

InterfaceAdds
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
Accept the most general type you need in parameters (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

TypeGood forLookup
List<T>Ordered items, access by indexO(1) by index, O(n) by value
Dictionary<TKey, TValue>Find a value by keyO(1) on average
HashSet<T>Unique items, fast ContainsO(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
}
An iterator method is lazy: its body does not run when you call it, only when the result is enumerated, one item at a time.
Because of laziness, argument checks inside an iterator method also run late, at the first MoveNext, not at the call.

Check yourself

  1. What is the main benefit of generics in C#?
  2. What does the constraint where T : new() require?
  3. Which interface provides only iteration with foreach?
  4. Which collection gives average O(1) Contains checks and stores unique items?
  5. When does the body of a method using yield return start executing?
  6. Which collection is first in, first out?
  7. where T : struct allows T to be string.
  8. Which parameter type is the most flexible for a method that only loops over its input?

Take the quiz on Brainbotox

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:

TypeSignature
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
In a 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);
An 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

  1. What is a delegate in C#?
  2. In Func<int, string, bool>, what is the return type?
  3. Which delegate type fits a method that takes a string and returns nothing?
  4. int factor = 2; Func<int,int> f = x => x * factor; factor = 10; What does f(3) return?
  5. What can code outside a class do with a public event of that class?
  6. Why write Paid?.Invoke(this, amount) and not Paid(this, amount)?
  7. Forgetting to unsubscribe from an event on a long-lived object can keep the subscriber alive in memory.
  8. What happens when a multicast delegate with three methods is invoked?

Take the quiz on Brainbotox

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

OperatorPurpose
WhereFilter
SelectTransform each item (projection)
SelectManyFlatten a sequence of sequences
OrderBy, ThenBySort
GroupByGroup items by a key
JoinMatch items of two sequences on a key
Any, All, ContainsTests that return bool
Count, Sum, Min, Max, AverageAggregates
Distinct, Skip, TakeRemove duplicates, paging
ToList, ToArray, ToDictionaryRun the query and store the result

First, Single and their OrDefault forms

MethodEmpty sequenceMore than one match
First()ThrowsReturns the first
FirstOrDefault()Returns default (null, 0)Returns the first
Single()ThrowsThrows
SingleOrDefault()Returns defaultThrows

Deferred execution

A LINQ query is a description of work. It runs only when you enumerate it (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 4
Enumerating the same query twice does the work twice (and hits the database twice). Call ToList() 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>
RunsIn memory, in your processAt the data source (for example SQL)
Lambdas areCompiled 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();
With a database, keep the query as IQueryable until filtering, sorting and paging are expressed, then materialise it.

Check yourself

  1. When does a LINQ query such as numbers.Where(n => n > 1) actually execute?
  2. What does First() do on an empty sequence?
  3. What does Single() do when two elements match?
  4. Which operator flattens a list of lists into one sequence?
  5. 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()?
  6. What is the key difference between IQueryable<T> and IEnumerable<T> with a database?
  7. Enumerating the same deferred LINQ query twice executes it twice.
  8. Which method is the efficient way to test whether a sequence has at least one element matching a condition?

Take the quiz on Brainbotox

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 typeUse for
TaskAn async method with no result
Task<T>An async method that returns a T
async voidEvent 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

Blocking on async code with .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.
Forgetting to await a task means the code continues before the work is done and exceptions go unobserved.

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 s

Cancellation 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.

By convention, name async methods with the suffix Async and accept a CancellationToken as the last parameter.

Check yourself

  1. What does await do when the awaited operation has not finished yet?
  2. Which return type should an async method with no result normally use?
  3. Why is async void dangerous outside event handlers?
  4. Which call runs two independent async operations concurrently and waits for both?
  5. What is the risk of calling .Result on an incomplete Task?
  6. For a heavy CPU-bound calculation in a desktop app, what keeps the UI responsive?
  7. Cancellation with CancellationToken forcibly kills the running thread.
  8. Where is an exception thrown inside an async Task method observed?

Take the quiz on Brainbotox

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")
};
Arms are tested from top to bottom and the first match wins, so put the most specific patterns first. If no arm matches at run time, a switch expression throws 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
Do not create a 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

LifetimeA new instance is createdTypical use
TransientEvery time it is requestedLight, stateless services
ScopedOnce per scope (per HTTP request in ASP.NET Core)DbContext, per-request state
SingletonOnce for the whole applicationCaches, configuration; must be thread-safe
Captive dependency: a singleton that takes a scoped service in its constructor keeps that one instance for the life of the application. A singleton must not depend on scoped services.
The container disposes the IDisposable services it creates, at the end of their scope. Do not dispose injected services yourself.

Check yourself

  1. What does if (shape is Circle c) do?
  2. In what order are the arms of a switch expression evaluated?
  3. Why does IDisposable exist when .NET has a garbage collector?
  4. In ASP.NET Core, how often is a Scoped service created?
  5. Which lifetime is the usual choice for an EF Core DbContext?
  6. What is a captive dependency?
  7. What is the main benefit of constructor injection against an interface?
  8. A Singleton service used by concurrent requests must be thread-safe.

Take the quiz on Brainbotox