In .NET we find many immutable collections, not just ImmutableList but also ImmutableArray and ImmutableDictionary. None of them can be modified at runtime.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
class Program
{
// Part 1: use immutable collections as fields.
static readonly ImmutableArray<string> _colors = [
"blue",
"aqua",
"cerulean"];
static readonly ImmutableList<int> _sizes = [10, 20, 15, 0];
static readonly ImmutableDictionary<string, bool> _items = ImmutableDictionary.CreateRange(
[KeyValuePair.Create(
"computer", true),
KeyValuePair.Create(
"desk", false),
KeyValuePair.Create(
"monitor", true)]);
public static void Main()
{
// Part 2: display strings in ImmutableArray.
Console.WriteLine(
"ARRAY LENGTH: {0}", _colors.Length);
foreach (string value in _colors)
{
Console.WriteLine(value);
}
// Part 3: loop over ImmutableList.
Console.WriteLine(
"LIST COUNT: {0}", _sizes.Count);
foreach (int value in _sizes)
{
Console.WriteLine(value);
}
// Part 4: loop over ImmutableDictionary.
Console.WriteLine(
"DICTIONARY COUNT: {0}", _items.Count);
foreach (var pair in _items)
{
Console.WriteLine(pair);
}
// Part 5: call Add on ImmutableList, creating a new immutable collection copy.
var sizesPlusOne = _sizes.Add(700);
Console.WriteLine(
"LIST COUNT: {0}", _sizes.Count);
Console.WriteLine(
"LIST+1 COUNT: {0}", sizesPlusOne.Count);
foreach (int value in sizesPlusOne)
{
Console.WriteLine(value);
}
}
}
ARRAY LENGTH: 3
blue
aqua
cerulean
LIST COUNT: 4
10
20
15
0
DICTIONARY COUNT: 3
[monitor, True]
[desk, False]
[computer, True]
LIST COUNT: 4
LIST+1 COUNT: 5
10
20
15
0
700