Introduction
Okay, so this may not be the most efficient code – so you may not want to use this in a context where milli seconds matter. But say you have a model class (returned by another library or from an API) and you need to extend it by adding a single property to it. The simplest way to do this is to derive a new class, add the property to it and then to add a constructor that copy-constructs from base to derived. Bit of a hassle having to copy every single property though, although I’d imagine some of those new AI powered IDEs could auto-generate code for you. Even then, if the base class ever changes, you will need to update this constructor and if you forget to do that, there’s a risk of random buggy behavior. So, what’s the hack? Use JsonConvert
to serialize the base object, then deserialize it to derived and then populate the new field or fields that’s been added to derived.
Using the code
static void Main()
{
ModelEx model = Foo(new Model
{
Id = 1000,
Name = "Mary Miller",
Description = "Senior Accountant"
});
model.Enabled = true;
}
private static ModelEx Foo(Model model)
{
var json = JsonConvert.SerializeObject(model);
return JsonConvert.DeserializeObject<ModelEx>(json);
}
class ModelEx : Model
{
public bool Enabled { get; set; }
}
class Model
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
As a commenter pointed out, you don't need to use Newtonsoft for this. You can use the more native System.Text.Json
classes, if you prefer. But if your codebase predominantly uses Newtonsoft, you can stay with that.
var json = JsonSerializer.Serialize(model);
return JsonSerializer.Deserialize<ModelEx>(json);
References
Nish Nishant is a technology enthusiast from Columbus, Ohio. He has over 20 years of software industry experience in various roles including Chief Technology Officer, Senior Solution Architect, Lead Software Architect, Principal Software Engineer, and Engineering/Architecture Team Leader. Nish is a 14-time recipient of the Microsoft Visual C++ MVP Award.
Nish authored C++/CLI in Action for Manning Publications in 2005, and co-authored Extending MFC Applications with the .NET Framework for Addison Wesley in 2003. In addition, he has over 140 published technology articles on CodeProject.com and another 250+ blog articles on his WordPress blog. Nish is experienced in technology leadership, solution architecture, software architecture, cloud development (AWS and Azure), REST services, software engineering best practices, CI/CD, mentoring, and directing all stages of software development.
Nish's Technology Blog :
voidnish.wordpress.com