Lesson 9 of 9
Mini Project: Product Catalog CLI Tool
Build a CLI product catalog tool using modern C# 12: records for data models, primary constructors, pattern matching for output formatting, async file I/O, LINQ for filtering/sorting, and the Result<T> pattern for error handling.
Quick Quiz - C# 12 & .NET 8 Runtime
Clean CLI Tool Architecture
// Program.cs - leverages C# 12 features throughout
using System.Text.Json;
// ━━ Domain ━━
public record Product(
string Id,
string Name,
decimal Price,
string Category,
int Stock)
{
public bool IsAvailable => Stock > 0;
public string PriceLabel => Price.ToString("C");
}
// ━━ Result pattern ━━
public record Result<T>(bool IsSuccess, T? Value = default, string? Error = null)
{
public static Result<T> Ok(T value) => new(true, value);
public static Result<T> Fail(string error) => new(false, Error: error);
}
// ━━ Repository with primary constructor ━━
public class JsonProductRepository(string filePath, ILogger logger)
{
public async Task<Result<List<Product>>> LoadAllAsync(CancellationToken ct = default)
{
try
{
if (!File.Exists(filePath))
return Result<List<Product>>.Ok(new List<Product>());
await using var stream = File.OpenRead(filePath);
var products = await JsonSerializer.DeserializeAsync<List<Product>>(stream, cancellationToken: ct);
return Result<List<Product>>.Ok(products ?? new List<Product>());
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to load products from {FilePath}", filePath);
return Result<List<Product>>.Fail($"Failed to load: {ex.Message}");
}
}
public async Task<Result<Unit>> SaveAllAsync(List<Product> products, CancellationToken ct = default)
{
try
{
await using var stream = File.Create(filePath);
await JsonSerializer.SerializeAsync(stream, products,
new JsonSerializerOptions { WriteIndented = true }, ct);
return Result<Unit>.Ok(Unit.Value);
}
catch (Exception ex)
{
return Result<Unit>.Fail($"Failed to save: {ex.Message}");
}
}
}
// ━━ Service with LINQ filtering ━━
public static IEnumerable<Product> Filter(
IEnumerable<Product> products,
string? category = null,
decimal? maxPrice = null,
bool availableOnly = false) =>
products
.Where(p => category is null || p.Category.Equals(category, StringComparison.OrdinalIgnoreCase))
.Where(p => maxPrice is null || p.Price <= maxPrice)
.Where(p => !availableOnly || p.IsAvailable)
.OrderBy(p => p.Name);
// ━━ Display with pattern matching ━━
static void PrintProduct(Product p) =>
Console.WriteLine(p switch
{
{ IsAvailable: false } => $"[OUT OF STOCK] {p.Name} - {p.PriceLabel}",
{ Stock: < 10 } => $"[LOW STOCK: {p.Stock}] {p.Name} - {p.PriceLabel}",
{ Category: "Electronics" } => $"[TECH] {p.Name} - {p.PriceLabel} ({p.Stock} in stock)",
_ => $"{p.Name} - {p.PriceLabel} ({p.Stock} in stock)"
});
public record Unit { public static Unit Value = new(); }
interface ILogger { void LogError(Exception ex, string msg, params object[] args); }Tip
Tip
Practice Mini Project Product Catalog CLI Tool in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of Mini Project Product Catalog CLI Tool from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Mini Project Product Catalog CLI Tool is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?