ReadOnlyCollection vs duplicating list

I’m working on an achievement system that I can import in my projects.

I want to expose a list of all achievements while making sure the user cannot modify the list outside of its initialization.

I’ve thought of 2 ways, something like this:

public static ReadOnlyCollection<Achievement> Achievements { get; private set; }

and then something like this

public static List<Achievement> Achievements { get { return achievements.ToList(); } }

The first one will force me and potential other users to use the ObjectModel namespace when fetching the list and I would prefer avoiding that, for the sake of making it as easy as possible to integrate.

Second option will generate garbage on every call.

Ideally I’d like a solution that doesn’t involve using infrequently used namespaces and that doesn’t generate garbage.

Hoping someone more savvy than me can elaborate on whether or not there’s a third solution/point out mistakes in my reasoning.

Does it need to be a List? How about implementing an enumerator and exposing IEnumerable instead?

1 Like

Thank you, that will definitely solve it!

Was unfamiliar with those, had to do a bit of reading. Here’s my implementation. Works fine! I’m unsure if there are any red flags.

public class Achievements : IEnumerable<Achievement>
{
    private IList<Achievement> achievements;

    public Achievements(IList<Achievement> achievements)
    {
        this.achievements = achievements;
    }

    public IEnumerator<Achievement> GetEnumerator()
    {
        foreach (Achievement achievement in achievements)
        {
            yield return achievement;
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}