ImmutableList vs List in C#

Shervan360 1,481 Reputation points
2021-11-15T00:38:22.573+00:00

Hello,

What is the difference between these? Output is the same.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;


namespace HelloWorld
{ 
  class Person
  {
    public int Age { get; private set;}
    public Person(int _age)
    {
      Age = _age;
    }
  }
  class Program
    {
        static void Main(string[] args)
        {
         List<Person> listOfPerson = new List<Person>();
           listOfPerson.Add(new Person(10));
           listOfPerson.Add(new Person(20));
           listOfPerson.Add(new Person(30));

          foreach (var item in listOfPerson)
          {
            System.Console.WriteLine(item.Age);
          }
        }
    }
}

and

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;

namespace HelloWorld
{ 
  class Person
  {
    public int Age { get; private set;}
    public Person(int _age)
    {
      Age = _age;
    }
  }
  class Program
    {
        static void Main(string[] args)
        {
          ImmutableList<Person> listOfPerson = ImmutableList.Create<Person>();
          listOfPerson = listOfPerson.Add(new Person(10));
          listOfPerson = listOfPerson.Add(new Person(20));
          listOfPerson = listOfPerson.Add(new Person(30));

          foreach (var item in listOfPerson)
          {
            System.Console.WriteLine(item.Age);
          }
        }
    }
}
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,298 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Jiale Xue - MSFT 34,201 Reputation points Microsoft Vendor
    2021-11-15T08:23:24.367+00:00

    Hi @Shervan360 ,

    Here is the documentation on ImmutableList<T> and List<T>.

    In terms of differences:

    ImmutableList<T> has no public constructor. List<T> has a constructor.

    They all have Item[Int32] and Count properties, ImmutableList<T> has IsEmpty property, and List<T> has Capacity property.

    ImmutableList<T> is thread-safe, while List<T> is thread-safe under correct operation.

    Regarding the immutability of ImmutableLIst<T>, you can refer to Eric's explanation.

    Best Regards,
    Jiale Xue.

    --------
    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread


  2. Bruce (SqlWork.com) 56,851 Reputation points
    2021-11-15T22:25:46.247+00:00

    an ImmutableList is one you can not add or delete items from. The add / delete operations create a new list. The advantage of them when passed to a method, the method knows the list can not change, that is the list is read only. the item in list may or may not be immutable items.

    while the list itself is thread safe, assigning to a variable shared across threads is not unless proper locking is used. so if you pass to a thread via closure, be sure not to modify the variable. also the objects in the list may not be thread safe.

    0 comments No comments

  3. Karen Payne MVP 35,196 Reputation points
    2021-11-16T11:41:22.657+00:00

    Suppose a request is made for data from a database that should not be changed, this is a case for ImmutableList . So it depends on your business rules which path to take.

    The following prevents add/remove but with auto-properties we can still change properties

    public static IReadOnlyList<Categories> GetCategoriesList()  
    {  
        using var context = new NorthwindContext();  
        return context.Categories.ToList().ToImmutableList();  
    }  
      
    public static readonly IReadOnlyList<Categories> CategoriesList = GetCategoriesList();  
    

    To prevent add/remove and property changes

    public class FromDatabaseMock  
    {  
        public static IReadOnlyList<Person> People()  
        {  
            return  new List<Person>()  
            {  
                new ("Karen", "Payne", new List<string>()),   
                new("Mary", "Jones", new List<string>())  
            };  
        }  
    }  
    public class Person  
    {  
        public Person(string firstName, string lastName, List<string> items)  
        {  
            FirstName = firstName;  
            LastName = lastName;  
            Items = items;  
        }  
        public string LastName { get; }  
        public string FirstName { get; }  
        public List<string> Items { get; }  
    }  
    

    149792-figure1.png

    Another example, get possible time zones for a DateTimeOffset, we don't want the user to alter the collection.

    In a static class

    /// <summary>  
    /// Get possible time zones for a DateTimeOffset  
    /// </summary>  
    /// <param name="offsetTime"></param>  
    /// <returns>time zone names</returns>  
    public static ImmutableList<string> PossibleTimeZones(this DateTimeOffset offsetTime)  
    {  
        List<string> list = new();  
        TimeSpan offset = offsetTime.Offset;  
      
        ReadOnlyCollection<TimeZoneInfo> timeZones = TimeZoneInfo.GetSystemTimeZones();  
      
        list.AddRange(from TimeZoneInfo timeZone in timeZones  
            where timeZone.GetUtcOffset(offsetTime.DateTime).Equals(offset)  
            select timeZone.DaylightName);  
      
        return list.ToImmutableList();  
    }  
    

    current is a nullable DateTimeOffset

    149768-figure2.png

    0 comments No comments