todo_json.cs in C#
A task list that survives restarts: JSON in, JSON out.
// todo_json: a tiny task list persisted as JSON in the temp directory
using System.Text.Json;
var path = Path.Combine(Path.GetTempPath(), "todo.json");
var opts = new JsonSerializerOptions { WriteIndented = true };
var items = File.Exists(path)
? JsonSerializer.Deserialize<List<Item>>(File.ReadAllText(path), opts)
: new List<Item>();
items.Add(new Item("write the report", false));
items.Add(new Item("ship the release", false));
items[0] = items[0] with { Done = true };
File.WriteAllText(path, JsonSerializer.Serialize(items, opts));
var reloaded = JsonSerializer.Deserialize<List<Item>>(
File.ReadAllText(path), opts);
foreach (var item in reloaded)
{
var mark = item.Done ? "x" : " ";
Console.WriteLine($"[{mark}] {item.Title}");
}
Console.WriteLine($"{reloaded.Count(i => !i.Done)} open");
File.Delete(path);
record Item(string Title, bool Done);
How it works
- The file loads if present; a fresh list stands in if not.
withmarks an item done without mutating the record.- Round-tripping through disk proves the persistence works.
Keywords and builtins used here
Itemboolfalseforeachinnewrecordstringtrueusingvarwith
The run, in numbers
- Lines
- 27
- Characters to type
- 860
- Tokens
- 199
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 133 seconds.
Step 2 of 2 in Encore, step 17 of 17 in The .NET library.