C
C#14mo ago
nathanAjacobs

❔ Are there read only collections that don't box enumerators?

ReadOnlyCollection<T> boxes struct enumerators since it stores IList<T> internally. ImmutableList<T> does not box enumerator, but I actually want to publically expose a List as read only and privately be able to modify it.
7 Replies
reflectronic
reflectronic14mo ago
you mean, like, a collection type which wraps another collection type, which does not box the enumerator through GetEnumerator? it is not possible to write something like that in C#. there is no abstraction which allows for that
nathanAjacobs
nathanAjacobsOP14mo ago
Yes exactly
reflectronic
reflectronic14mo ago
i mean. it is possible to make your own IFastEnumerable<T, TEnumerator> interface or whatever. it would be possible using an interface like that. but List does not implement that interface
nathanAjacobs
nathanAjacobsOP14mo ago
I mean couldn't something like this achieve it?
public class ReadOnlyList<T> : IReadOnlyList<T>, IList<T>, IList
{
private readonly List<T> _list;

public ReadOnlyList(List<T> list)
{
if (list is null)
throw new ArgumentNullException(nameof(list));

_list = list;
}

public List<T>.Enumerator GetEnumerator()
{
return _list.GetEnumerator();
}
}
public class ReadOnlyList<T> : IReadOnlyList<T>, IList<T>, IList
{
private readonly List<T> _list;

public ReadOnlyList(List<T> list)
{
if (list is null)
throw new ArgumentNullException(nameof(list));

_list = list;
}

public List<T>.Enumerator GetEnumerator()
{
return _list.GetEnumerator();
}
}
It basically is what ReadOnlyCollection<T> is but instead of storing IList<T> it stores List<T> internally
reflectronic
reflectronic14mo ago
oh, i see. i thought you wanted something that worked for any IList<T> without boxing but, no, there isn't a class in the BCL with a struct enumerator that wraps another collection
nathanAjacobs
nathanAjacobsOP14mo ago
Yeah I thought so, I'll just have to implement these manually then. Ty!
Accord
Accord14mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server