© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•14mo ago•
12 replies
Crater

Mutable-by-copy pattern?

Curious if anyone has any clever solutions for this, or can point out if I'm missing some knowledge. Basically I've set up some data that's totally immutable (I hope, at least - if I missed something or there's a better approach, feel free to point it out).

This is a simplified example similar to what I've got:
public readonly record struct ImmutableThing
{
    public readonly string Name;
    public readonly int Number;
    public readonly ImmutableArray<byte> Stuff;
    public ImmutableThing(string name, int number, params byte[] stuff)
    {
        Name = name;
        Number = number;
        Stuff = stuff.AsReadOnly();
    }
}
public readonly record struct ImmutableThing
{
    public readonly string Name;
    public readonly int Number;
    public readonly ImmutableArray<byte> Stuff;
    public ImmutableThing(string name, int number, params byte[] stuff)
    {
        Name = name;
        Number = number;
        Stuff = stuff.AsReadOnly();
    }
}

But if I wanted to have a mutable version of this data then I'd need to copy it, naturally. The obvious answer is just to have a record struct that's identical to this except not
readonly
readonly
, with all single value types losing their
readonly
readonly
as well, and
ImmutableArray
ImmutableArray
becomes an array, etc.

Is there any way around that, though? Some way to copy between immutable and mutable without needing essentially a duplicate of the entire type? Maybe some sort of wrapping/boxing that still allows reads, but not modifying the values (or collection members?) without copying?

A duplicate wouldn't be that cumbersome for the example given obviously, but with a much larger data structure (and a more complicated and layered construction process, and many different types that would ideally follow this pattern) it starts to seem like an unattractive option.

Any ideas/alternatives? Not married to the types/primitives (e.g.
record struct
record struct
) in question either if there's something that might be more fitting, but the idea is generally to keep it in the realm of "fast and solid value-typed data" I guess.
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

What is meant by copy on build.
C#CC# / help
4y ago
✅ Copy files generated by command to build output
C#CC# / help
3y ago
✅ Immutable object with mutable clone
C#CC# / help
3y ago
Directory Copy
C#CC# / help
2y ago