Home  Dotnet   How to crea ...

how to create immutable list in csharp dotnet

In C#, you can create an immutable list of strings using the System.Collections.Immutable namespace, which provides a variety of immutable collection types. To create an immutable list of strings, you'll typically use the ImmutableList<T> class.

Here's how you can create and work with an immutable list of strings:

Step-by-Step Guide

  1. Install the System.Collections.Immutable Package:

    If you don't already have the System.Collections.Immutable package, you'll need to install it via NuGet. You can do this using the NuGet Package Manager in Visual Studio or via the Package Manager Console.

    Using the Package Manager Console:

    Install-Package System.Collections.Immutable
    
  2. Import the Namespace:

    At the top of your C# file, import the System.Collections.Immutable namespace:

    using System.Collections.Immutable;
    
  3. Create an Immutable List:

    You can create an immutable list using the ImmutableList class. Here are a few examples:

    using System;
    using System.Collections.Immutable;
    
    class Program
    {
        static void Main()
        {
            // Creating an immutable list using ImmutableList.Create
            ImmutableList<string> immutableList1 = ImmutableList.Create("one", "two", "three");
    
            // Creating an immutable list from an existing collection
            var list = new List<string> { "four", "five", "six" };
            ImmutableList<string> immutableList2 = ImmutableList.ToImmutableList(list);
    
            // Adding an item to an immutable list (creates a new list)
            ImmutableList<string> newList = immutableList1.Add("four");
    
            // Printing the lists
            Console.WriteLine("Immutable List 1:");
            foreach (var item in immutableList1)
            {
                Console.WriteLine(item);
            }
    
            Console.WriteLine("\nImmutable List 2:");
            foreach (var item in immutableList2)
            {
                Console.WriteLine(item);
            }
    
            Console.WriteLine("\nNew List after adding an item:");
            foreach (var item in newList)
            {
                Console.WriteLine(item);
            }
        }
    }
    

Explanation

  1. Creating an Immutable List:

    • ImmutableList.Create("one", "two", "three") creates an immutable list with the specified elements.
    • ImmutableList.ToImmutableList(list) converts an existing collection (in this case, a List<string>) into an immutable list.
  2. Adding an Item:

    • immutableList1.Add("four") creates a new immutable list with the added element. The original list (immutableList1) remains unchanged.

Immutable List Characteristics

Published on: Jun 27, 2024, 05:13 AM  
 

Comments

Add your comment