Is it possible to take following class and make it generic? It's a simple JSON file database that does simple Create and Update to task objects and propagates to a JSON file.
How do I make this generic? Do I put the generic type on the class or in the methods?
I want to be able to do this to any type of object.
public class TaskRepository
{
string _filePath = Path.Combine(Directory.GetCurrentDirectory(), "dbFile.json");
internal List<Task> Get()
{
var json = File.ReadAllText(_filePath);
var tasks = JsonConvert.DeserializeObject<List<Task>>(json);
return tasks;
}
internal Task Save(Task task)
{
List<Task> tasks = Get();
if (tasks == null) tasks = new List<Task>();
//Try and find incoming task
var itemIndex = tasks.FindIndex(t => t.Id == task.Id);
//Check if it exists
if (itemIndex > 0)
{
//update existing task
tasks[itemIndex] = task;
}
else
{
//add as new task
int newIndex = tasks.Count + 1;
task.Id = newIndex;
task.DateCreated = DateTime.Now;
tasks.Add(task);
}
//Update file
WriteData(tasks);
return task;
}
private bool WriteData(List<Task> tasks)
{
var json = JsonConvert.SerializeObject(tasks, Formatting.Indented);
System.IO.File.WriteAllText(_filePath, json);
return true;
}
}
class Task
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime DateCreated { get; set; }
}