C# Cheatsheet

Async and .NET

Use this C# reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Task and async/await

using System.Threading.Tasks;

static async Task<string> LoadAsync()
{
    await Task.Delay(100);  // stand-in for real I/O
    return "done";
}

public static async Task Main()
{
    string result = await LoadAsync();
    Console.WriteLine(result);
}

Use async for I/O waiting: HTTP calls, database calls, file operations, timers. It does not automatically make CPU work faster. Never block with .Result or .Wait() inside async code, that invites deadlocks.

Cancellation and Combinators

using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));

static async Task<string> FetchAsync(HttpClient http, string url, CancellationToken ct)
{
    using var res = await http.GetAsync(url, ct);
    res.EnsureSuccessStatusCode();
    return await res.Content.ReadAsStringAsync(ct);
}

var http = new HttpClient();
string[] pages = await Task.WhenAll(
    FetchAsync(http, "https://a.example.com", cts.Token),
    FetchAsync(http, "https://b.example.com", cts.Token));

Task<string> firstDone = await Task.WhenAny(
    FetchAsync(http, "https://a.example.com", cts.Token),
    FetchAsync(http, "https://b.example.com", cts.Token));
string fastest = await firstDone;

Accept a CancellationToken as the last parameter and pass it through every await. Task.WhenAll runs work concurrently and rethrows the first failure; Task.WhenAny returns the first task to finish (even if it faulted).

Async Streams and ValueTask

using System.Runtime.CompilerServices;

static async IAsyncEnumerable<int> CountAsync(
    [EnumeratorCancellation] CancellationToken ct = default)
{
    for (int i = 0; i < 3; i++)
    {
        await Task.Delay(100, ct);
        yield return i;
    }
}

await foreach (int n in CountAsync())
{
    Console.WriteLine(n);
}

// ValueTask avoids a Task allocation when the result is often ready synchronously
static ValueTask<int> ReadCachedAsync() => new(42);

IAsyncEnumerable<T> + await foreach streams results as they arrive. Await a ValueTask exactly once and do not store it; default to Task unless profiling says otherwise.

Parallel CPU Work

Parallel.For(0, 100, i => DoWork(i));

await Parallel.ForEachAsync(urls, cts.Token, async (url, ct) =>
{
    await ProcessAsync(url, ct);
});

Parallelism and async are different. Async waits efficiently; parallelism uses multiple cores. Parallel.ForEachAsync bounds concurrent async work (set MaxDegreeOfParallelism via ParallelOptions).

dotnet CLI

dotnet --version
dotnet new console -n Demo
dotnet run
dotnet build
dotnet test
dotnet add package Microsoft.EntityFrameworkCore
dotnet list package --outdated
dotnet publish -c Release

The SDK manages project creation, restore, build, run, test, and packages. JSON needs no package: System.Text.Json ships in the base library.

Minimal .csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
</Project>

TargetFramework chooses the .NET runtime surface (net10.0 is the current LTS; net8.0 remains in support). Nullable enables reference nullability analysis.

Useful Namespaces

NamespaceUse
SystemConsole, Math, DateTime, basic types
System.Collections.GenericList, Dictionary, HashSet, Queue, Stack, PriorityQueue
System.LinqLINQ extension methods
System.IOFiles, streams, paths
System.TextStringBuilder, encodings
System.Text.JsonJsonSerializer, JsonNode
System.Threading.TasksTask, async support
System.Net.HttpHTTP clients