3

Possible Duplicate:
Immutable List in C#

Is it possible to make a list immutable

Community
  • 1
  • 1
user673453
  • 167
  • 1
  • 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

5

You can use ReadOnlyCollection<T> instead.

Colin Pickard
  • 45,724
  • 13
  • 98
  • 148
  • 1
    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
  • 122,218
  • 32
  • 205
  • 338