Cloning Class Using System.Text.Json in .NET 8

The .NET 8 Preview 7 introduces the JsonInclude attribute in System.Text.Json. We can use this new attribute to indicate that a class’s property or field should be included for serialization and deserialization, even if it is not public. It can be helpful when we wish to restrict the access level of our class members while still using them for JSON operations.

DotNET

Using this new property (JsonInclude), we can use Serialize and Deserialize to generate a clone from a List object.

Here I design a sample, cloning a class with an internal property and changing the value.

using System.Text.Json.Serialization;
using System.Text.Json;

var names = new List<MyNameId>();

for (var n = 65; n <= 65+25; n++)
{ 
    names.Add(new MyNameId() { Name = ((char)n).ToString() + " character", Id = n-65 });
}

string json = JsonSerializer.Serialize(names);
var newNames = JsonSerializer.Deserialize<List<MyNameId>>(json);
var copyNames = names;

newNames[0].Name = newNames[0].Name = "AA"; // Not change the original
copyNames[0].Name = copyNames[0].Name = "AAA"; // Change the original

Console.WriteLine(".NET 8 Preview 7");
// Property Name
Console.WriteLine(names[0].Name);
Console.WriteLine(copyNames[0].Name);
Console.WriteLine(newNames[0].Name);

// Prepert Test
Console.WriteLine(names[0].Test);
Console.WriteLine(copyNames[0].Test);
Console.WriteLine(newNames[0].Test);

Console.ReadKey();


public class MyNameId
{
    public string Name;

    [JsonInclude]
    internal int Id;

    [JsonInclude]
    internal string Test => Id + "_" + Name;
}

Console output

.NET 8

If you try to run this code on .NET 6/7, you will receive this error.

Exception unhandled

I hope this helps you to quickly clone Lists in C#.