Introduction
Tracking habits can help you build consistency, boost productivity, and improve your lifestyle. In this article, we will develop a simple Habit Tracker using C# and JSON, which allows users to log and check off daily habits. This app is great for those learning how to persist data locally and build interactive console-based programs.
Prerequisites
- .NET SDK (6.0 or later)
- Basic understanding of C#
- A code editor like Visual Studio or VS Code
Step 1. Define the Habit Model**
public class Habit
{
public string Name { get; set; }
public List<DateTime> CompletedDates { get; set; } = new List<DateTime>();
}
Step 2. JSON Storage Handler
using System.Text.Json;
public static class HabitStorage
{
private const string FileName = "habits.json";
public static List<Habit> Load()
{
if (!File.Exists(FileName)) return new List<Habit>();
var json = File.ReadAllText(FileName);
return JsonSerializer.Deserialize<List<Habit>>(json) ?? new List<Habit>();
}
public static void Save(List<Habit> habits)
{
var json = JsonSerializer.Serialize(habits, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(FileName, json);
}
}
Step 3: Program Logic (Program.cs)
class Program
{
static List<Habit> habits = HabitStorage.Load();
static void Main()
{
while (true)
{
Console.Clear();
Console.WriteLine("=== Habit Tracker ===");
Console.WriteLine("1. Add Habit");
Console.WriteLine("2. Mark Habit Completed");
Console.WriteLine("3. View Progress");
Console.WriteLine("4. Exit");
Console.Write("Select option: ");
string input = Console.ReadLine();
switch (input)
{
case "1": AddHabit(); break;
case "2": MarkCompleted(); break;
case "3": ViewProgress(); break;
case "4": HabitStorage.Save(habits); return;
default: Console.WriteLine("Invalid choice."); break;
}
Console.WriteLine("\nPress Enter to continue...");
Console.ReadLine();
}
}
static void AddHabit()
{
Console.Write("Enter habit name: ");
string name = Console.ReadLine();
habits.Add(new Habit { Name = name });
HabitStorage.Save(habits);
Console.WriteLine("Habit added.");
}
static void MarkCompleted()
{
if (!habits.Any())
{
Console.WriteLine("No habits to mark.");
return;
}
for (int i = 0; i < habits.Count; i++)
Console.WriteLine($"{i + 1}. {habits[i].Name}");
Console.Write("Select habit number: ");
if (int.TryParse(Console.ReadLine(), out int index) && index > 0 && index <= habits.Count)
{
habits[index - 1].CompletedDates.Add(DateTime.Today);
HabitStorage.Save(habits);
Console.WriteLine("Marked as completed.");
}
else
{
Console.WriteLine("Invalid input.");
}
}
static void ViewProgress()
{
if (!habits.Any())
{
Console.WriteLine("No habits tracked.");
return;
}
foreach (var habit in habits)
{
int count = habit.CompletedDates.Count(d => d.Month == DateTime.Today.Month);
Console.WriteLine($"{habit.Name}: {count} times this month");
}
}
}