1

Possible Duplicate:
Immutable List in C#

Is it possible to make a list immutable

Community
  • 1
  • 1
user673453
  • 147
  • 4
  • 16
  • 3
    [Immutable List in C#](http://stackoverflow.com/questions/4680035/immutable-list-in-c) – jfs Apr 21 '11 at 10:22
  • Immutable how? Please give an example of usage. – Matt Ellen Apr 21 '11 at 10:22
  • Which list do you mean? Try it with `list.Enabled = false;` ... – Aykut Çevik Apr 21 '11 at 10:22
  • Those that come across this thread without checking the duplicate may want to know that .NET Framework 4.5 introduced an `ImmutableList`: https://msdn.microsoft.com/en-us/library/dn467185(v=vs.111).aspx – fuglede Sep 07 '17 at 07:13

2 Answers2

3

You can use ReadOnlyCollection<T> instead.

Colin Pickard
  • 44,639
  • 13
  • 95
  • 146
  • It can be wise to `var readonly = new ReadOnlyCollection(new List(ints));` so that you don't accidently make changes to the wrapped collection as I discovered here http://alicebobandmallory.com/articles/2011/01/01/lazy-evaluation-is-no-friend-of-mutable-state – Jonas Elfström Apr 21 '11 at 10:39
2

List<T>.AsReadOnly() returns a readonly wrapper, so that you can't add/remove/replace elements.

To be truly immutable, the type T must be an immutable Type.

Joe
  • 118,426
  • 28
  • 194
  • 329