Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ToReadOnlyCollection #15

Open
bgrainger opened this issue Dec 31, 2018 · 4 comments
Open

ToReadOnlyCollection #15

bgrainger opened this issue Dec 31, 2018 · 4 comments
Labels
new analyzer Suggestion for a new analyzer to add

Comments

@bgrainger
Copy link
Member

See Faithlife/FaithlifeUtility#5.

ToReadOnlyCollection has somewhat unpredictable behaviour, depending on the nature of the IEnumerable<T> it's called on:

  • ReadOnlyCollection<T>: returns same object
  • List<T>: returns an .AsReadOnly() wrapper around it; changes the caller makes to the list will be reflected in this wrapper, which is usually undesirable behaviour when the return value of this call is stored in a field by a constructor
  • IEnumerable<T>: calls .ToList().AsReadOnly() and gets a new immutable list

Furthermore, this method returns ReadOnlyCollection<T>, which we would like to phase out.

Most usages of this method should be replaced with AsReadOnlyList(); some should change to .ToList().AsReadOnly().

N.B. enforcing this rule would be a huge breaking change. An intermediate step might be to enforce that .ToReadOnlyCollection() may not be used to initialize fields or properties in constructors and that .ToList().AsReadOnly() must be used instead. (This addresses the buggiest and least frequent usage.)

@bgrainger bgrainger added the new analyzer Suggestion for a new analyzer to add label Dec 31, 2018
@RobertBolender
Copy link

Furthermore, this method returns ReadOnlyCollection, which we would like to phase out.

Could you elaborate on this?

@bgrainger
Copy link
Member Author

@RobertBolender
Copy link

So we specifically want to phase out its use as a return value, correct?

@bgrainger
Copy link
Member Author

Yes, phase it out in public APIs; there's nothing wrong with using it in an implementation to enforce read-only-ness. The suggestions above include using .ToList().AsReadOnly() which returns a ReadOnlyCollection<T>.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
new analyzer Suggestion for a new analyzer to add
Development

No branches or pull requests

2 participants