Examples
C# worked examples: tiny console programs that demonstrate idiomatic modern .NET.
C# — examples
EXAMPLE
// ===== Example 1: HTTP GET to JSON =====
using System.Net.Http.Json;
public record GithubRepo(string Name, int StargazersCount);
using var http = new HttpClient();
var repo = await http.GetFromJsonAsync<GithubRepo>("https://api.github.com/repos/dotnet/runtime");
Console.WriteLine($"{repo!.Name}: {repo.StargazersCount}");
// ===== Example 2: minimal API =====
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/healthz", () => Results.Json(new { ok = true }));
app.MapGet("/users/{id:int}", (int id) => Results.Json(new { id, name = "Alex" }));
app.MapPost("/users", (User u) => Results.Created($"/users/{u.Id}", u));
app.Run();
record User(int Id, string Name);
// ===== Example 3: LINQ aggregation =====
record Order(string Customer, decimal Total);
var orders = new List<Order> {
new("alice", 49.95m),
new("alice", 19.00m),
new("bob", 100m),
};
var byCustomer = orders.GroupBy(o => o.Customer).Select(g => new {
Customer = g.Key,
Total = g.Sum(o => o.Total),
Count = g.Count(),
});
foreach (var row in byCustomer) Console.WriteLine(row);
// ===== Example 4: async file processing =====
using System.Text.Json;
public record LogLine(string Level, string Msg);
await foreach (var line in File.ReadLinesAsync("log.json")) {
var entry = JsonSerializer.Deserialize<LogLine>(line);
if (entry?.Level == "error") Console.WriteLine(entry.Msg);
}
// ===== Example 5: cancellation token =====
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
try {
var data = await http.GetStringAsync("https://example.com", cts.Token);
Console.WriteLine(data.Length);
} catch (TaskCanceledException) {
Console.WriteLine("timeout");
}
// ===== Example 6: parallel work =====
var ids = Enumerable.Range(1, 100);
await Parallel.ForEachAsync(ids, async (id, ct) => {
var r = await http.GetAsync($"/api/items/{id}", ct);
// ...
});
// ===== Example 7: pattern matching =====
public abstract record Shape;
public record Circle(double Radius) : Shape;
public record Square(double Side) : Shape;
double Area(Shape s) => s switch {
Circle c => Math.PI * c.Radius * c.Radius,
Square sq => sq.Side * sq.Side,
_ => throw new ArgumentException(nameof(s)),
};
// ===== Example 8: typed config via options =====
public class StripeOptions {
public string ApiKey { get; init; } = "";
public string WebhookSecret { get; init; } = "";
}
// In Program.cs:
builder.Services.Configure<StripeOptions>(builder.Configuration.GetSection("Stripe"));
// In a service:
public class PaymentService(IOptions<StripeOptions> options) {
public string Key => options.Value.ApiKey;
}
// ===== Example 9: result type via discriminated unions =====
public abstract record Result<T>;
public record Ok<T>(T Value) : Result<T>;
public record Err<T>(string Message) : Result<T>;
Result<int> Divide(int a, int b) => b == 0 ? new Err<int>("div by zero") : new Ok<int>(a / b);
var r = Divide(10, 0);
var msg = r switch {
Ok<int> ok => $"got {ok.Value}",
Err<int> err => $"failed: {err.Message}",
_ => "?",
};
// ===== Patterns =====
// - records for DTOs + value objects
// - Minimal APIs for tiny services
// - LINQ for collection transforms
// - Cancellation tokens at every async boundary
// - Pattern matching for closed hierarchies
// ===== Pitfalls =====
// - .Result on Tasks (deadlock risk)
// - async void except for event handlers
// - LINQ on hot loops -> consider span / loops
// - Disabling nullable warnings
Why it matters
Modern C# in 100 lines: HTTP+JSON, minimal API, LINQ, async file reading, cancellation, parallel work, pattern matching, options, sum types. Master these idioms and most .NET code falls into shape.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Discussion
Loading…