79350996

Date: 2025-01-13 01:20:57
Score: 2.5
Natty:
Report link

I phrased my question in the StackOverflow friendly way of 'should not be looking for opinion', but as its looking like the proper answer to my question might just be "No", I do appreciate the ideas that have been mentioned here, so I thought I'd put an idea im toying with up, thanks to TheodorZoulias advice to focus on my main concerns.

This idea requires an Immutable collection to initialize the class, but then returns it as an IReadOnly, alleviating my main concerns about both interfaces: I can be sure the data passed in will never be modified, and that users of the class won't be tripped up by mutation looking methods (eg Add)

public record class Class
{
    private readonly ImmutableList<string> _students = ImmutableList<string>.Empty;

    public IReadOnlyList<string> Students => _students;

    // Bit weird.. mainly to allow 'with', which is a nice feature of records 
    public ImmutableList<string> StudentsInit { init => _students = value ?? ImmutableList<string>.Empty; } 
    
    public Class(){}

    public Class(ImmutableList<string> students)
    {
        _students = students ?? ImmutableList<string>.Empty; // probably better to just throw if value is null..
    }
}

As you can see there is some funkyness here that could be improved by just rolling my own immutable collections sans the mutation looking functions, but in lieu of that..

Reasons:
  • Blacklisted phrase (0.5): thanks
  • Blacklisted phrase (1): StackOverflow
  • RegEx Blacklisted phrase (3): thanks to TheodorZoulias advice
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • High reputation (-1):
Posted by: matt