Go deeper with generics and constraints, advanced LINQ (GroupBy/Join), and JSON serialization using System.Text.Json.
Master reusable types, powerful queries, and modern data formats.
Box<T> with a read-only property and method:
class Box<T>
{
public T Value { get; private set; }
public Box(T value) { Value = value; }
public void SetValue(T value) { Value = value; }
public void Describe() => Console.WriteLine($"T is {typeof(T).Name}");
}static class Utils
{
public static T Max<T>(T a, T b) where T : IComparable<T>
{
return a.CompareTo(b) >= 0 ? a : b;
}
}Box<int> and Box<string>, print their values, call Describe(), and use Utils.Max for ints and strings.where) to express capabilities required (class, struct, interfaces, parameterless ctor)Box<int> value: 42
Box<string> value: hello
T is Int32
Max int: 10
Max string: orange
class Box<T> { T Value { get; } }where T : IComparable<T>new Box<int>(42), new Box<string>("hi")typeof(T).Name shows the type argument at runtimeReview feedback below
class Student { public int Id; public string Name; public int DeptId; }
class Department { public int Id; public string Name; }
Make List<Student> and List<Department> with sample data.Join, ordered by student name.Select into anonymous types.ToList() or ToDictionary() where appropriate.using System.Linq;GroupJoin can compute aggregates from related itemsToList() to execute immediatelyStudents per department:
Engineering: 3
Marketing: 2
Join sample:
Alice -> Engineering
Bob -> Engineering
Chloe -> Marketing
David -> Engineering
Eve -> Marketing
using System.Linq;students.GroupBy(s => s.DeptId).Join(depts, g => g.Key, d => d.Id, ...).ToList() to execute queriesfrom s in students join d in depts on s.DeptId equals d.Id select ...Review feedback below
System.Text.Json with options.class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Email { get; set; }
}
2. Serialize with options: Use JsonSerializerOptions { WriteIndented = true }.Person.[JsonPropertyName("...")] annotations (requires System.Text.Json.Serialization).PropertyNameCaseInsensitive help with casing mismatchesSystem.Text.Json in modern .NET for performanceSerialized JSON:
{
"Name": "Alice",
"Age": 25,
"Email": "alice@example.com"
}
Deserialized: Alice (25) - alice@example.com
using System.Text.Json; (+ ...Serialization if using attributes)new JsonSerializerOptions { WriteIndented = true }JsonSerializer.Serialize(obj, options)JsonSerializer.Deserialize<Type>(json)Review feedback below