Adding a Clone method to a C# record

 
 
  • Gérald Barré

#Adding a Clone method to a C# record

When using records, creating a copy with with is concise:

C#
var sample = new Sample("meziantou");
_ = sample with { };

public record Sample(string Value);

This works well, but sample with { } is not always obvious as a discoverable Clone API for consumers.

##Why public Sample Clone() is not allowed

Records already have compiler-generated clone behavior used by with. Because of that, declaring your own instance Clone() in the record is rejected:

C#
public record Sample(string Value)
{
    // ❌ Not allowed
    public Sample Clone()
    {
        return new Sample(Value);
    }
}

##Add an explicit Clone extension method

If you want a clear, discoverable API, add an extension method:

C#
public static class SampleExtensions
{
    public static Sample Clone(this Sample sample)
    {
        return sample with { };
    }
}

Then consumers can write:

C#
var sample = new Sample("meziantou");
var clone = sample.Clone();

This keeps record semantics intact while exposing a method name that can be easier to understand in some APIs.

##Additional resources

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?