I have the following class
public abstract class Settings
{
private string _filename;
protected virtual void defaults()
{
}
public static T Load<T>(string filename) where T : Settings, new()
{
T theSetting;
if (File.Exists(filename))
{
var reader = new StreamReader(filename);
var configJson = reader.ReadToEnd();
reader.Close();
theSetting = System.Text.Json.JsonSerializer.Deserialize<T>(configJson);
}
else
{
theSetting = new T();
theSetting.defaults();
}
theSetting._filename = filename;
theSetting.Save();
return theSetting;
}
public void Save()
{
var writer = new StreamWriter(_filename);
writer.Write(JsonSerializer.Serialize(this));
writer.Close();
}
public void SaveAs(string filename)
{
_filename = filename;
Save();
}
}
I know that polymorphic is not supported in .NET Core but I found several answers here
Is polymorphic deserialization possible in System.Text.Json?
The problem is that all the answers are for situations where we have a model class But in my example, the model class is not specified and is created by the user.
I also tried this answer and it worked without any problems But I do not want to use an external library in my project